Skip to content

Commit

Permalink
fix formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
djeck1432 committed Oct 26, 2024
1 parent 12d0954 commit 6f013c6
Show file tree
Hide file tree
Showing 12 changed files with 144 additions and 127 deletions.
5 changes: 2 additions & 3 deletions web_app/alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
execution modes (online and offline). It integrates with SQLAlchemy models
and provides the core functionality needed for database schema version control.
"""

from logging.config import fileConfig

from sqlalchemy import engine_from_config
Expand Down Expand Up @@ -76,9 +77,7 @@ def run_migrations_online() -> None:
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@
Create Date: 2024-10-24 18:56:29.399344
"""

import logging
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

logger = logging.getLogger(__name__)

# revision identifiers, used by Alembic.
revision = 'a009512f5362'
down_revision = 'b705d1435b64'
revision = "a009512f5362"
down_revision = "b705d1435b64"
branch_labels = None
depends_on = None

Expand All @@ -21,30 +24,36 @@ def column_exists(table_name, column_name):
"""Utility function to check if a column exists in the table."""
bind = op.get_bind()
inspector = inspect(bind)
columns = [col['name'] for col in inspector.get_columns(table_name)]
columns = [col["name"] for col in inspector.get_columns(table_name)]
return column_name in columns


def upgrade() -> None:
"""Upgrade the database."""

if column_exists('position', 'start_price'):
print("Column 'start_price' already exists, skipping creation.")
if column_exists("position", "start_price"):
logger.info("Column 'start_price' already exists, skipping creation.")
else:
op.add_column('position', sa.Column('start_price', sa.DECIMAL(), nullable=False))
print("Column 'start_price' added to the 'position' table.")
op.add_column(
"position", sa.Column("start_price", sa.DECIMAL(), nullable=False)
)
logger.info("Column 'start_price' added to the 'position' table.")
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('position', 'start_price',
existing_type=sa.DOUBLE_PRECISION(precision=53),
type_=sa.DECIMAL(),
existing_nullable=False)
op.alter_column(
"position",
"start_price",
existing_type=sa.DOUBLE_PRECISION(precision=53),
type_=sa.DECIMAL(),
existing_nullable=False,
)
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade the database."""

if column_exists('position', 'start_price'):
print("Column 'start_price' exists, downgrading.")
op.drop_column('position', 'start_price')
if column_exists("position", "start_price"):
logger.info("Column 'start_price' exists, downgrading.")
op.drop_column("position", "start_price")
else:
print("Column 'start_price' already removed, skipping.")
logger.info("Column 'start_price' already removed, skipping.")
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
Create Date: 2024-10-14 21:13:19.784033
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy import text


# revision identifiers, used by Alembic.
revision = 'b705d1435b64'
down_revision = 'd71e1e3e800f'
revision = "b705d1435b64"
down_revision = "d71e1e3e800f"
branch_labels = None
depends_on = None

Expand All @@ -30,9 +31,10 @@ def column_exists(table_name: str, column_name: str) -> bool:
"""
bind = op.get_bind()
inspector = Inspector.from_engine(bind)
columns = [column.get('name') for column in inspector.get_columns(table_name)]
columns = [column.get("name") for column in inspector.get_columns(table_name)]
return column_name in columns


def enum_type_exists(enum_name: str) -> bool:
"""Check if an enum type exists in the database.
Expand All @@ -43,9 +45,10 @@ def enum_type_exists(enum_name: str) -> bool:
bool: True if the enum type exists, False otherwise
"""
bind = op.get_bind()
result = bind.execute(text(
"SELECT EXISTS (SELECT 1 FROM pg_type WHERE typname = :enum_name);"
), {"enum_name": enum_name})
result = bind.execute(
text("SELECT EXISTS (SELECT 1 FROM pg_type WHERE typname = :enum_name);"),
{"enum_name": enum_name},
)
return result.scalar()


Expand All @@ -59,27 +62,28 @@ def upgrade() -> None:
- Drops the 'deployed_transaction_hash' column from the 'user' table if it exists
"""
# Create enum type 'status_enum' if it doesn't exist
if not enum_type_exists('status_enum'):
if not enum_type_exists("status_enum"):
op.execute("CREATE TYPE status_enum AS ENUM ('pending', 'opened', 'closed')")

# Add status column to position table if it doesn't exist
if not column_exists('position', 'status'):
if not column_exists("position", "status"):
op.add_column(
'position',
"position",
sa.Column(
'status',
sa.Enum('pending', 'opened', 'closed', name='status_enum'),
nullable=True
)
"status",
sa.Enum("pending", "opened", "closed", name="status_enum"),
nullable=True,
),
)

# Add contract_address column to user table if it doesn't exist
if not column_exists('user', 'contract_address'):
op.add_column('user', sa.Column('contract_address', sa.String(), nullable=True))
if not column_exists("user", "contract_address"):
op.add_column("user", sa.Column("contract_address", sa.String(), nullable=True))

# Drop deployed_transaction_hash column from user table if it exists
if column_exists('user', 'deployed_transaction_hash'):
op.drop_column('user', 'deployed_transaction_hash')
if column_exists("user", "deployed_transaction_hash"):
op.drop_column("user", "deployed_transaction_hash")


def downgrade() -> None:
"""Downgrade the database schema.
Expand All @@ -91,25 +95,25 @@ def downgrade() -> None:
- Adds the 'deployed_transaction_hash' column to the 'user' table if it doesn't exist
"""
# Drop status column from position table if it exists
if column_exists('position', 'status'):
op.drop_column('position', 'status')
if column_exists("position", "status"):
op.drop_column("position", "status")

# Drop the enum type if there are no columns using it
if enum_type_exists('status_enum'):
if enum_type_exists("status_enum"):
op.execute("DROP TYPE status_enum")

# Drop contract_address column from user table if it exists
if column_exists('user', 'contract_address'):
op.drop_column('user', 'contract_address')
if column_exists("user", "contract_address"):
op.drop_column("user", "contract_address")

# Add deployed_transaction_hash column to user table if it doesn't exist
if not column_exists('user', 'deployed_transaction_hash'):
if not column_exists("user", "deployed_transaction_hash"):
op.add_column(
'user',
"user",
sa.Column(
'deployed_transaction_hash',
"deployed_transaction_hash",
sa.VARCHAR(),
autoincrement=False,
nullable=True
)
nullable=True,
),
)
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
Create Date: 2024-10-12 20:41:29.852081
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine import reflection


# revision identifiers, used by Alembic.
revision = 'd71e1e3e800f'
revision = "d71e1e3e800f"
down_revision = None
branch_labels = None
depends_on = None
Expand All @@ -30,33 +31,36 @@ def upgrade() -> None:
# Create 'user' table if it does not exist
bind = op.get_bind()
inspector = reflection.Inspector.from_engine(bind)
if 'user' not in inspector.get_table_names():
if "user" not in inspector.get_table_names():
op.create_table(
'user',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('is_contract_deployed', sa.Boolean(), nullable=True),
sa.Column('wallet_id', sa.String(), nullable=False),
sa.Column('deployed_transaction_hash', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
"user",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("is_contract_deployed", sa.Boolean(), nullable=True),
sa.Column("wallet_id", sa.String(), nullable=False),
sa.Column("deployed_transaction_hash", sa.String(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f('ix_user_wallet_id'), 'user', ['wallet_id'], unique=False)
op.create_index(op.f("ix_user_wallet_id"), "user", ["wallet_id"], unique=False)

# Create 'position' table if it does not exist
if 'position' not in inspector.get_table_names():
if "position" not in inspector.get_table_names():
op.create_table(
'position',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.Column('token_symbol', sa.String(), nullable=False),
sa.Column('amount', sa.String(), nullable=False),
sa.Column('multiplier', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['user.id']),
sa.PrimaryKeyConstraint('id')
"position",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("user_id", sa.UUID(), nullable=False),
sa.Column("token_symbol", sa.String(), nullable=False),
sa.Column("amount", sa.String(), nullable=False),
sa.Column("multiplier", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["user.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_position_user_id"), "position", ["user_id"], unique=False
)
op.create_index(op.f('ix_position_user_id'), 'position', ['user_id'], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade the database schema.
Expand All @@ -65,8 +69,8 @@ def downgrade() -> None:
- Drop 'user' table if it exists
"""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_position_user_id'), table_name='position')
op.drop_table('position')
op.drop_index(op.f('ix_user_wallet_id'), table_name='user')
op.drop_table('user')
op.drop_index(op.f("ix_position_user_id"), table_name="position")
op.drop_table("position")
op.drop_index(op.f("ix_user_wallet_id"), table_name="user")
op.drop_table("user")
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion web_app/alembic/versions/e69320e12cc7_add_airdrop_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def upgrade() -> None:
def downgrade() -> None:
"""
Perform the downgrade migration to remove the 'airdrop' table from the database if it exists.
This migration drops the 'airdrop' table and its associated indexes on `user_id`
This migration drops the 'airdrop' table and its associated indexes on `user_id`
and `is_claimed`.
It is intended to reverse the changes made in the `upgrade` function, allowing
for a rollback of the database schema to the state before the 'airdrop' table was added.
Expand Down
41 changes: 19 additions & 22 deletions web_app/api/position.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,63 +11,60 @@
)
from web_app.api.serializers.position import PositionFormData
from web_app.contract_tools.constants import (
TokenParams,
TokenParams,
TokenMultipliers,
)
)
from web_app.contract_tools.mixins.deposit import DepositMixin
from web_app.db.crud import PositionDBConnector

router = APIRouter() # Initialize the router
position_db_connector = PositionDBConnector() # Initialize the PositionDBConnector


class TokenMultiplierResponse(BaseModel):
"""
This class defines the structure of the response for the token multiplier
This class defines the structure of the response for the token multiplier
endpoint, encapsulating a dictionary where each token symbol:
(e.g., "ETH", "STRK")
(e.g., "ETH", "STRK")
is mapped to its respective multiplier value.
### Parameters:
- **multipliers**: A dictionary containing token symbols as keys:
(e.g., "ETH", "STRK", "USDC")
- **multipliers**: A dictionary containing token symbols as keys:
(e.g., "ETH", "STRK", "USDC")
and their respective multipliers as values.
### Returns:
A structured JSON response with each token and its multiplier.
"""

multipliers: dict[str, float]

class Config:
"""
Metadata for TokenMultiplierResponse
Metadata for TokenMultiplierResponse
with example JSON response format in **schema_extra**.
"""

schema_extra = {
"example": {
"multipliers": {
"ETH": 5.0,
"STRK": 2.5,
"USDC": 5.0
}
}
"example": {"multipliers": {"ETH": 5.0, "STRK": 2.5, "USDC": 5.0}}
}


@router.get(
"/api/get-multipliers",
tags=["Position Operations"],
response_model=TokenMultiplierResponse,
summary="Get token multipliers",
response_description="Returns token multipliers",
)
"/api/get-multipliers",
tags=["Position Operations"],
response_model=TokenMultiplierResponse,
summary="Get token multipliers",
response_description="Returns token multipliers",
)
async def get_multipliers() -> TokenMultiplierResponse:
"""
This Endpoint retrieves the multipliers for tokens like ETH, STRK, and USDC.
"""
multipliers = {
"ETH": TokenMultipliers.ETH,
"STRK": TokenMultipliers.STRK,
"USDC": TokenMultipliers.USDC
"USDC": TokenMultipliers.USDC,
}
return TokenMultiplierResponse(multipliers=multipliers)

Expand Down
Loading

0 comments on commit 6f013c6

Please sign in to comment.