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

feat(platform): Implement Auto-Top-Up credits capability #9278

Open
wants to merge 4 commits into
base: zamilmajdy/secrt-1018-phase-2-create-payment-method-crud
Choose a base branch
from

Conversation

majdyz
Copy link
Contributor

@majdyz majdyz commented Jan 15, 2025

image

Changes πŸ—οΈ

Added auto-top-up credits capability:

  • Added autoTopUpConfig column on user
  • Added autoTopUp form UI
  • Added payment charge logic for top_up_credits
  • Added auto-top-up logic on spend_credits

Checklist πŸ“‹

For code changes:

  • I have clearly listed my changes in the PR description
  • I have made a test plan
  • I have tested my changes according to the test plan:
    • ...
Example test plan
  • Create from scratch and execute an agent with at least 3 blocks
  • Import an agent from file upload, and confirm it executes correctly
  • Upload agent to marketplace
  • Import an agent from marketplace and confirm it executes correctly
  • Edit an agent from monitor, and confirm it executes correctly

For configuration changes:

  • .env.example is updated or already compatible with my changes
  • docker-compose.yml is updated or already compatible with my changes
  • I have included a list of my configuration changes in the PR description (under Changes)
Examples of configuration changes
  • Changing ports
  • Adding new services that need to communicate with each other
  • Secrets or environment variable changes
  • New or infrastructure changes such as databases

@majdyz majdyz requested a review from kcze January 15, 2025 17:56
@majdyz majdyz requested a review from a team as a code owner January 15, 2025 17:56
@majdyz majdyz requested review from Bentlybro and removed request for a team January 15, 2025 17:56
@github-actions github-actions bot added platform/frontend AutoGPT Platform - Front end platform/backend AutoGPT Platform - Back end size/l labels Jan 15, 2025
Copy link

PR Reviewer Guide πŸ”

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 πŸ”΅πŸ”΅πŸ”΅πŸ”΅βšͺ
πŸ§ͺΒ No relevant tests
πŸ”’Β Security concerns

Sensitive information exposure:
The payment intent metadata stored in the transaction record may contain sensitive payment method details that should be filtered before storage.

⚑ Recommended focus areas for review

Race Condition

The auto top-up logic in spend_credits() checks balance after transaction is committed, which could lead to multiple concurrent top-ups if balance drops below threshold simultaneously.

# Auto top-up if balance just went below threshold due to this transaction.
auto_top_up = await get_auto_top_up(user_id)
if balance < auto_top_up.threshold <= balance - cost:
    try:
        await self.top_up_credits(user_id=user_id, amount=auto_top_up.amount)
    except Exception as e:
        # Failed top-up is not critical, we can move on.
        logger.error(
            f"Auto top-up failed for user {user_id}, balance: {balance}, amount: {auto_top_up.amount}, error: {e}"
        )
Error Handling

The top_up_credits() method attempts payment with all available payment methods but doesn't properly handle individual payment failures or distinguish between different error types.

for payment_method in payment_methods:
    if amount == 0:
        setup_intent = stripe.SetupIntent.create(
            customer=customer_id,
            usage="off_session",
            confirm=True,
            payment_method=payment_method.id,
            automatic_payment_methods={
                "enabled": True,
                "allow_redirects": "never",
            },
        )
        if setup_intent.status == "succeeded":
            return

    else:
        payment_intent = stripe.PaymentIntent.create(
            amount=amount,
            currency="usd",
            description="AutoGPT Platform Credits",
            customer=customer_id,
            off_session=True,
            confirm=True,
            payment_method=payment_method.id,
            automatic_payment_methods={
                "enabled": True,
                "allow_redirects": "never",
            },
        )
        if payment_intent.status == "succeeded":
            await self._add_transaction(
                user_id=user_id,
                amount=amount,
                transaction_type=CreditTransactionType.TOP_UP,
                transaction_key=payment_intent.id,
                metadata=Json({"payment_intent": payment_intent}),
                is_active=True,
            )
            return
Input Validation

The auto top-up form lacks client-side validation to ensure amount is greater than threshold before submission.

const submitAutoTopUpConfig = (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  const form = e.currentTarget;
  const formData = new FormData(form);
  const amount = parseInt(formData.get("topUpAmount") as string);
  const threshold = parseInt(formData.get("threshold") as string);
  toastOnFail("update auto top-up config", () =>
    updateAutoTopUpConfig(amount, threshold).then(() => {
      toast({ title: "Auto top-up config updated! πŸŽ‰" });
    }),
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
platform/backend AutoGPT Platform - Back end platform/frontend AutoGPT Platform - Front end Review effort [1-5]: 4 size/l
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

1 participant