Skip to content

Make tipbot accounting atomic and harden balance recovery - #10

Open
reubenyap wants to merge 5 commits into
masterfrom
codex/tipbot-accounting-safety
Open

reubenyap wants to merge 5 commits into
masterfrom
codex/tipbot-accounting-safety

Conversation

@reubenyap

@reubenyap reubenyap commented Sep 13, 2026

Copy link
Copy Markdown
Member

Replace floating-point, separate balance writes with integer groth and MongoDB transactions. Durable deposit, tip, envelope and withdrawal records make replay and recovery idempotent. The commits separate the accounting/migration foundation from recovery and precision hardening.

Withdrawals reserve funds before broadcast, retain uncertain outcomes for manual review, and refund only verified pre-spend rejections. Recovery does not assign transactions from approximate matches. The changes also reconcile missing conflicted deposits, recover zero-balance envelope replays, preserve exact RPC amounts, prevent overlapping bot processes, and normalize legacy null transaction IDs before creating the unique index. RPC/Telegram adapters and deployment requirements are updated accordingly; username-based tips are disabled in favor of reply-based recipient IDs.

Wallet lookup failures now flag individual deposits for review without blocking reconciliation. Withdrawal reviews refresh when evidence changes, deposit address validation runs only for /deposit, and startup failures exit nonzero.

Validation:

  • Python 3.10.20: python -B -m unittest discover -s tests -q, 58 passed.
  • Python 3.12.13: python -B -W ignore::DeprecationWarning -m unittest discover -s tests -q, 58 passed.
  • py_compile passed for all three production Python files and four test modules.
  • git diff --check origin/master and current-base git merge-tree passed.

Live MongoDB replica-set, Firo and Telegram integration testing remains unperformed. Unit tests use an in-memory database fake. Historical balances have not been reconciled against a production wallet.

Deployment requires a MongoDB replica set, backup and offline legacy migration. Uncertain withdrawals and stale ownership records after a forced shutdown require operator review, as documented in the README.

Overlaps the accounting proposals in #5 and #6; it does not depend on them. #7, #8 and #9 touch the same flows and require adaptation/rebasing before combining.

Reserve withdrawals before broadcast, journal deposits and transfers transactionally, and migrate legacy balances and addresses with quarantine for unresolved withdrawals. Update the RPC and Telegram adapters and deployment requirements for this accounting model.
Keep uncertain spends locked, require manual transaction matching, recover deposit conflicts and envelope replays, and protect migrations with exclusive database ownership. Preserve exact RPC amounts and normalize legacy null transaction IDs before indexing.
@reubenyap
reubenyap marked this pull request as ready for review September 13, 2026 16:06
@codeant-ai

codeant-ai Bot commented Sep 13, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR 8c3f10e Sep 13, 2026 · 16:06 16:09

@codeant-ai

codeant-ai Bot commented Sep 13, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-13T16:21:14.391847Z 8c3f10e Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Sep 13, 2026
@codeant-ai

codeant-ai Bot commented Sep 13, 2026

Copy link
Copy Markdown

User description

Replace floating-point, separate balance writes with integer groth and MongoDB transactions. Durable deposit, tip, envelope and withdrawal records make replay and recovery idempotent. Two commits separate the accounting/migration foundation from recovery and precision hardening.

Withdrawals reserve funds before broadcast, retain uncertain outcomes for manual review, and refund only verified pre-spend rejections. Recovery does not assign transactions from approximate matches. The changes also reconcile missing conflicted deposits, recover zero-balance envelope replays, preserve exact RPC amounts, prevent overlapping bot processes, and normalize legacy null transaction IDs before creating the unique index. RPC/Telegram adapters and deployment requirements are updated accordingly; username-based tips are disabled in favor of reply-based recipient IDs.

Validation:

  • Python 3.10.20: python -B -m unittest discover -s tests -q, 52 passed.
  • Python 3.12.13: python -B -W ignore::DeprecationWarning -m unittest discover -s tests -q, 52 passed.
  • py_compile passed for all three production Python files and four test modules.
  • git diff --check origin/master and current-base git merge-tree passed.

Draft pending live MongoDB replica-set, Firo and Telegram integration testing. Unit tests use an in-memory database fake. Historical balances have not been reconciled against a production wallet.

Deployment requires a MongoDB replica set, backup and offline legacy migration. Uncertain withdrawals and stale ownership records after a forced shutdown require operator review, as documented in the README.

Overlaps the accounting proposals in #5 and #6; it does not depend on them. #7, #8 and #9 touch the same flows and require adaptation/rebasing before combining.


CodeAnt-AI Description

Make tipbot accounting precise, transactional, and recoverable

What Changed

  • Balances, tips, deposits, envelopes, and withdrawals now use exact integer groth amounts and transactional updates, preventing partial transfers and rounding losses
  • Withdrawals reserve funds before broadcast; uncertain wallet outcomes remain locked and are not retried automatically, while only verified rejections are refunded
  • Deposit and withdrawal recovery handles conflicts, reorganizations, interrupted operations, and replayed updates without applying credits or debits twice
  • Legacy balances and records are migrated with unresolved withdrawals quarantined for review; retired shared deposit addresses are replaced and later payments are flagged instead of assigned arbitrarily
  • Only one bot process can operate on a database at a time, and Telegram updates are acknowledged safely after successful processing
  • Username-based tips are replaced with reply-based tipping, and envelope claims require the original Telegram message
  • Deployment now requires a MongoDB replica set, explicit offline migration confirmation, and current Firo Core and Python dependencies
  • Added coverage for accounting recovery, precision, replay safety, RPC failures, process ownership, and envelope behavior

Impact

✅ No rounding loss in balances and tips
✅ Fewer duplicate charges and credits after retries
✅ Uncertain withdrawals remain recoverable without unsafe refunds

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Comment thread api/firo_wallet_api.py
Comment on lines +65 to +87
def get_txs_list(self, page_size=1000):
transactions = []
skip = 0

# ponytail: full history scan favors correctness; move to a persisted
# listsinceblock cursor when wallet history makes this measurably slow.
while True:
response = self._rpc(
"listtransactions",
["*", page_size, skip],
request_id=2,
)
if response.get("error"):
return response

page = response["result"]
if not isinstance(page, list):
raise FiroTransportError("listtransactions returned a non-list result")
transactions.extend(page)
if len(page) < page_size:
response["result"] = transactions
return response
skip += len(page)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: page_size accepts zero or negative values, so an empty page never satisfies the exit condition and the loop repeatedly requests the same offset forever. [logic error]

Assessment: 🟠 Major · 🔁 Occurrence: Rarely

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** api/firo_wallet_api.py
**Line:** 65:87
**Comment:**
	*Logic Error: `page_size` accepts zero or negative values, so an empty page never satisfies the exit condition and the loop repeatedly requests the same offset forever.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment thread tipbot.py Outdated
self.create_send_tips_image(
self.user_id,
"{0:.8f}".format(amount),
receiver['first_name'],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The transfer commits before this lookup; a verified legacy recipient without first_name raises KeyError after receiving funds, so confirmations are never sent. [error handling]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tipbot.py
**Line:** 2168:2168
**Comment:**
	*Error Handling: The transfer commits before this lookup; a verified legacy recipient without `first_name` raises `KeyError` after receiving funds, so confirmations are never sent.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment thread update_address.py
Comment on lines +31 to 33
raise RuntimeError("getsparkdefaultaddress returned invalid data")
users = self.col_users.find({"Address": {"$in": default_addresses}})
for user in users:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: create_user_wallet() returns one address string, so this loop appends individual characters as separate addresses and corrupts affected users. [type error]

Assessment: 🔴 Critical · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** update_address.py
**Line:** 31:33
**Comment:**
	*Type Error: `create_user_wallet()` returns one address string, so this loop appends individual characters as separate addresses and corrupts affected users.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Require a positive integer before calling listtransactions so a zero-sized page cannot stall pagination. Cover rejected values without making an RPC request.
Fall back to the recipient Telegram ID when a legacy profile has no display name, so completed transfers still send both confirmations. Cover missing, empty and existing names without changing replay-safe balances.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8c3f10ee6e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tipbot.py Outdated
Comment thread tipbot.py
Comment thread tipbot.py
Comment thread tipbot.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant