Skip to content

Commit

Permalink
Merge branch 'main' into xai-crawlers
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey committed Feb 21, 2024
2 parents 10f3762 + 192961d commit 4906531
Show file tree
Hide file tree
Showing 25 changed files with 1,160 additions and 243 deletions.
28 changes: 28 additions & 0 deletions engineapi/alembic/versions/6d07739cb13e_live_at_for_metatx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Live at for metatx
Revision ID: 6d07739cb13e
Revises: 71e888082a6d
Create Date: 2023-12-06 14:33:04.814144
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '6d07739cb13e'
down_revision = '71e888082a6d'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('call_requests', sa.Column('live_at', sa.DateTime(timezone=True), nullable=True))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('call_requests', 'live_at')
# ### end Alembic commands ###
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Tx hash for call requests
Revision ID: 7191eb70e99e
Revises: 6d07739cb13e
Create Date: 2023-10-04 11:23:12.516797
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '7191eb70e99e'
down_revision = '6d07739cb13e'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('call_requests', sa.Column('tx_hash', sa.VARCHAR(length=256), nullable=True))
op.create_unique_constraint(op.f('uq_call_requests_tx_hash'), 'call_requests', ['tx_hash'])
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(op.f('uq_call_requests_tx_hash'), 'call_requests', type_='unique')
op.drop_column('call_requests', 'tx_hash')
# ### end Alembic commands ###
50 changes: 50 additions & 0 deletions engineapi/alembic/versions/71e888082a6d_leaderboard_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""leaderboard metadata
Revision ID: 71e888082a6d
Revises: cc80e886e153
Create Date: 2023-11-15 13:21:16.108399
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "71e888082a6d"
down_revision = "cc80e886e153"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"leaderboards",
sa.Column(
"blockchain_ids",
sa.ARRAY(sa.Integer()),
nullable=False,
server_default="{}",
),
)
op.add_column(
"leaderboards",
sa.Column(
"wallet_connect", sa.Boolean(), nullable=False, server_default="false"
),
)
op.add_column(
"leaderboards",
sa.Column(
"columns_names", postgresql.JSONB(astext_type=sa.Text()), nullable=True
),
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("leaderboards", "columns_names")
op.drop_column("leaderboards", "wallet_connect")
op.drop_column("leaderboards", "blockchain_ids")
# ### end Alembic commands ###
111 changes: 93 additions & 18 deletions engineapi/engineapi/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
import uuid
import logging

from bugout.data import BugoutResource, BugoutSearchResult
from bugout.data import (
BugoutResource,
BugoutSearchResult,
ResourcePermissions,
HolderType,
BugoutResourceHolder,
)
from eth_typing import Address
from hexbytes import HexBytes
import requests # type: ignore
Expand All @@ -16,7 +22,14 @@
from web3 import Web3
from web3.types import ChecksumAddress

from .data import Score, LeaderboardScore, LeaderboardConfigUpdate, LeaderboardConfig
from .data import (
Score,
LeaderboardScore,
LeaderboardConfigUpdate,
LeaderboardConfig,
LeaderboardPosition,
ColumnsNames,
)
from .contracts import Dropper_interface, ERC20_interface, Terminus_interface
from .models import (
DropperClaimant,
Expand Down Expand Up @@ -96,6 +109,10 @@ class LeaderboardVersionNotFound(Exception):
pass


class LeaderboardAssignResourceError(Exception):
pass


BATCH_SIGNATURE_PAGE_SIZE = 500

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -1268,7 +1285,7 @@ def get_leaderboard_score(

def get_leaderboard_positions(
db_session: Session,
leaderboard_id,
leaderboard_id: uuid.UUID,
limit: int,
offset: int,
version_number: Optional[int] = None,
Expand Down Expand Up @@ -1481,31 +1498,47 @@ def create_leaderboard(
title: str,
description: Optional[str],
token: Optional[Union[uuid.UUID, str]] = None,
wallet_connect: bool = False,
blockchain_ids: List[int] = [],
columns_names: ColumnsNames = None,
) -> Leaderboard:
"""
Create a leaderboard
"""

if columns_names is not None:
columns_names = columns_names.dict()

if not token:
token = uuid.UUID(MOONSTREAM_ADMIN_ACCESS_TOKEN)
try:
leaderboard = Leaderboard(title=title, description=description)
# deduplicate and sort
blockchain_ids = sorted(list(set(blockchain_ids)))

leaderboard = Leaderboard(
title=title,
description=description,
wallet_connect=wallet_connect,
blockchain_ids=blockchain_ids,
columns_names=columns_names,
)
db_session.add(leaderboard)
db_session.commit()

user = None
if token is not None:
user = bc.get_user(token=token)

resource = create_leaderboard_resource(
leaderboard_id=str(leaderboard.id),
token=token,
user_id=str(user.id) if user is not None else None,
)

leaderboard.resource_id = resource.id

db_session.commit()
except Exception as e:
db_session.rollback()
logger.error(f"Error creating leaderboard: {e}")
raise LeaderboardCreateError(f"Error creating leaderboard: {e}")

return leaderboard


Expand Down Expand Up @@ -1548,6 +1581,9 @@ def update_leaderboard(
leaderboard_id: uuid.UUID,
title: Optional[str],
description: Optional[str],
wallet_connect: Optional[bool],
blockchain_ids: Optional[List[int]],
columns_names: Optional[ColumnsNames],
) -> Leaderboard:
"""
Update a leaderboard
Expand All @@ -1561,6 +1597,23 @@ def update_leaderboard(
leaderboard.title = title
if description is not None:
leaderboard.description = description
if wallet_connect is not None:
leaderboard.wallet_connect = wallet_connect
if blockchain_ids is not None:
# deduplicate and sort
blockchain_ids = sorted(list(set(blockchain_ids)))
leaderboard.blockchain_ids = blockchain_ids

if columns_names is not None:
if leaderboard.columns_names is not None:
current_columns_names = ColumnsNames(**leaderboard.columns_names)

for key, value in columns_names.dict(exclude_none=True).items():
setattr(current_columns_names, key, value)
else:
current_columns_names = columns_names

leaderboard.columns_names = current_columns_names.dict()

db_session.commit()

Expand Down Expand Up @@ -1659,50 +1712,72 @@ def add_scores(
# leaderboard access actions


def create_leaderboard_resource(
leaderboard_id: str, token: Union[Optional[uuid.UUID], str] = None
) -> BugoutResource:
def create_leaderboard_resource(leaderboard_id: str, user_id: Optional[str] = None):
resource_data: Dict[str, Any] = {
"type": LEADERBOARD_RESOURCE_TYPE,
"leaderboard_id": leaderboard_id,
}

if token is None:
token = MOONSTREAM_ADMIN_ACCESS_TOKEN
try:
resource = bc.create_resource(
token=token,
token=MOONSTREAM_ADMIN_ACCESS_TOKEN,
application_id=MOONSTREAM_APPLICATION_ID,
resource_data=resource_data,
timeout=10,
)
except Exception as e:
raise LeaderboardCreateError(f"Error creating leaderboard resource: {e}")

if user_id is not None:
try:
bc.add_resource_holder_permissions(
token=MOONSTREAM_ADMIN_ACCESS_TOKEN,
resource_id=resource.id,
holder_permissions=BugoutResourceHolder(
holder_type=HolderType.user,
holder_id=user_id,
permissions=[
ResourcePermissions.ADMIN,
ResourcePermissions.READ,
ResourcePermissions.UPDATE,
ResourcePermissions.DELETE,
],
),
)
except Exception as e:
raise LeaderboardCreateError(
f"Error adding resource holder permissions: {e}"
)

return resource


def assign_resource(
db_session: Session,
leaderboard_id: uuid.UUID,
user_token: Union[uuid.UUID, str],
user_token: Optional[Union[uuid.UUID, str]] = None,
resource_id: Optional[uuid.UUID] = None,
):
"""
Assign a resource handler to a leaderboard
"""

### get user_name from token

user = None
if user_token is not None:
user = bc.get_user(token=user_token)

leaderboard = (
db_session.query(Leaderboard).filter(Leaderboard.id == leaderboard_id).one() # type: ignore
)

if resource_id is not None:
leaderboard.resource_id = resource_id
else:
# Create resource via admin token

resource = create_leaderboard_resource(
leaderboard_id=str(leaderboard_id),
token=user_token,
user_id=user.id if user is not None else None,
)

leaderboard.resource_id = resource.id
Expand Down
Loading

0 comments on commit 4906531

Please sign in to comment.