-
Notifications
You must be signed in to change notification settings - Fork 138
Improve timeout handling and error recovery #667
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| # CLAUDE.md | ||
|
|
||
| This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. | ||
|
|
||
| ## Project Overview | ||
|
|
||
| LNp2pBot is a Telegram bot that facilitates peer-to-peer Lightning Network trading. Users can create buy/sell orders for Bitcoin using Lightning Network hold invoices to ensure trustless transactions. | ||
|
|
||
| ## Development Commands | ||
|
|
||
| ### Build and Run | ||
| ```bash | ||
| npm start # Compile TypeScript and start bot | ||
| npm run dev # Compile and start with nodemon for development | ||
| npm run prestart # Compile TypeScript only | ||
| npm run predev # Compile TypeScript only | ||
| ``` | ||
|
|
||
| ### Code Quality | ||
| ```bash | ||
| npm run lint # ESLint code validation | ||
| npm run format # Format code with Prettier | ||
| ``` | ||
|
|
||
| ### Testing | ||
| ```bash | ||
| npm test # Run all tests with Mocha | ||
| npm run pretest # Compile tests only | ||
| ``` | ||
|
|
||
| ## Architecture | ||
|
|
||
| ### Core Structure | ||
| - **app.ts**: Main entry point, handles MongoDB connection and bot initialization | ||
| - **bot/**: Bot logic and command handlers | ||
| - **start.ts**: Bot initialization, command registration, and scheduled jobs | ||
| - **modules/**: Feature-specific modules (community, orders, dispute, etc.) | ||
| - **middleware/**: Authentication, validation, and context enhancement | ||
| - **models/**: MongoDB schemas (User, Order, Community, Dispute, etc.) | ||
| - **ln/**: Lightning Network integration (hold invoices, payments, subscriptions) | ||
| - **jobs/**: Scheduled background tasks for order management and payments | ||
| - **util/**: Shared utilities and helpers | ||
|
|
||
| ### Key Patterns | ||
|
|
||
| #### Context Enhancement | ||
| The bot uses custom context types that extend Telegraf's base context: | ||
| - `MainContext`: Adds i18n, user, and admin properties | ||
| - `CommunityContext`: Extends MainContext for community-specific features | ||
|
|
||
| #### Module Structure | ||
| Each feature module follows this pattern: | ||
| - `commands.ts`: Command handlers | ||
| - `actions.ts`: Action button handlers | ||
| - `messages.ts`: Message templates | ||
| - `scenes.ts`: Multi-step conversation flows | ||
| - `index.ts`: Module configuration and exports | ||
|
|
||
| #### Hold Invoice Pattern | ||
| The bot uses Lightning Network hold invoices for trustless escrow: | ||
| 1. Seller creates order | ||
| 2. Buyer takes order, seller pays hold invoice | ||
| 3. Funds are held until both parties confirm fiat exchange | ||
| 4. Hold invoice is settled or canceled based on dispute resolution | ||
|
|
||
| #### Job Scheduling | ||
| Background jobs handle critical functions: | ||
| - Pending payment retries | ||
| - Order expiration and cleanup | ||
| - Community earnings calculation | ||
| - Node health monitoring | ||
|
|
||
| ### Database Models | ||
| - **User**: Telegram users with trading history and preferences | ||
| - **Order**: Trading orders with status tracking and dispute handling | ||
| - **Community**: Telegram groups with custom fee structures | ||
| - **Dispute**: Conflict resolution with solver assignment | ||
| - **PendingPayment**: Failed payment retry queue | ||
|
|
||
| ### Environment Setup | ||
| Copy `.env-sample` to `.env` and configure: | ||
| - `BOT_TOKEN`: Telegram bot API token | ||
| - `LND_*`: Lightning Network node connection details | ||
| - `DB_*` or `MONGO_URI`: MongoDB connection | ||
| - `CHANNEL`: Public order announcement channel | ||
| - `ADMIN_CHANNEL`: Admin notifications | ||
|
|
||
| ### Testing | ||
| Tests are in TypeScript and use Mocha with Chai assertions. Test compilation uses a separate tsconfig.test.json that includes the tests directory. | ||
|
|
||
| ### Key Dependencies | ||
| - **telegraf**: Telegram bot framework | ||
| - **mongoose**: MongoDB ODM | ||
| - **lightning**: LND node integration | ||
| - **node-schedule**: Cron job scheduling | ||
| - **@grammyjs/i18n**: Internationalization | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,12 +14,21 @@ export const attemptPendingPayments = async (bot: Telegraf<CommunityContext>): P | |
| attempts: { $lt: process.env.PAYMENT_ATTEMPTS }, | ||
| is_invoice_expired: false, | ||
| community_id: null, | ||
| next_retry: { $lte: new Date() }, | ||
| }); | ||
| for (const pending of pendingPayments) { | ||
| const order = await Order.findOne({ _id: pending.order_id }); | ||
| try { | ||
| if (order === null) throw Error("Order was not found in DB"); | ||
| pending.attempts++; | ||
|
|
||
| // Calculate exponential backoff delay | ||
| const baseDelay = 5 * 60 * 1000; // 5 minutes | ||
| const exponentialDelay = baseDelay * Math.pow(2, pending.attempts - 1); | ||
| const maxDelay = 60 * 60 * 1000; // 1 hour max | ||
| const nextRetryDelay = Math.min(exponentialDelay, maxDelay); | ||
| pending.next_retry = new Date(Date.now() + nextRetryDelay); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @grunch this piece of code is duplicated, should it be extracted as a function? |
||
|
|
||
| if (order.status === 'SUCCESS') { | ||
| pending.paid = true; | ||
| await pending.save(); | ||
|
|
@@ -85,9 +94,25 @@ export const attemptPendingPayments = async (bot: Telegraf<CommunityContext>): P | |
| ); | ||
| await messages.rateUserMessage(bot, buyerUser, order, i18nCtx); | ||
| } else { | ||
| // Enhanced error handling for different payment failure types | ||
| if (payment && typeof payment === 'object' && 'error' in payment) { | ||
| pending.last_error = payment.error as string; | ||
|
|
||
| if (payment.error === 'TIMEOUT') { | ||
|
grunch marked this conversation as resolved.
|
||
| logger.warn(`Payment timeout for order ${order._id}, attempt ${pending.attempts}`); | ||
| } else if (payment.error === 'ROUTING_FAILED') { | ||
| logger.warn(`Routing failed for order ${order._id}, attempt ${pending.attempts}`); | ||
| } else { | ||
| logger.error(`Payment failed for order ${order._id}, attempt ${pending.attempts}, error: ${payment.error}`); | ||
| } | ||
| } else { | ||
| pending.last_error = 'PAYMENT_FAILED'; | ||
| logger.error(`Payment failed for order ${order._id}, attempt ${pending.attempts}`); | ||
| } | ||
|
|
||
| if ( | ||
| process.env.PAYMENT_ATTEMPTS !== undefined && | ||
| pending.attempts === parseInt(process.env.PAYMENT_ATTEMPTS) | ||
| pending.attempts >= parseInt(process.env.PAYMENT_ATTEMPTS) | ||
| ) { | ||
| order.paid_hold_buyer_invoice_updated = false; | ||
| await messages.toBuyerPendingPaymentFailedMessage( | ||
|
|
@@ -124,11 +149,19 @@ export const attemptCommunitiesPendingPayments = async (bot: Telegraf<CommunityC | |
| attempts: { $lt: process.env.PAYMENT_ATTEMPTS }, | ||
| is_invoice_expired: false, | ||
| community_id: { $ne: null }, | ||
| next_retry: { $lte: new Date() }, | ||
| }); | ||
|
|
||
| for (const pending of pendingPayments) { | ||
| try { | ||
| pending.attempts++; | ||
|
|
||
| // Calculate exponential backoff delay for community payments | ||
| const baseDelay = 5 * 60 * 1000; // 5 minutes | ||
| const exponentialDelay = baseDelay * Math.pow(2, pending.attempts - 1); | ||
| const maxDelay = 60 * 60 * 1000; // 1 hour max | ||
| const nextRetryDelay = Math.min(exponentialDelay, maxDelay); | ||
| pending.next_retry = new Date(Date.now() + nextRetryDelay); | ||
|
|
||
| // We check if this new payment is on flight | ||
| const isPending: boolean = await isPendingPayment(pending.payment_request); | ||
|
|
@@ -174,9 +207,22 @@ export const attemptCommunitiesPendingPayments = async (bot: Telegraf<CommunityC | |
| }) | ||
| ); | ||
| } else { | ||
| // Enhanced error handling for community payments | ||
| if (payment && typeof payment === 'object' && 'error' in payment) { | ||
| pending.last_error = payment.error as string; | ||
| logger.error( | ||
| `Community ${community.id}: Withdraw failed after ${pending.attempts} attempts, amount ${pending.amount} sats, error: ${payment.error}` | ||
| ); | ||
| } else { | ||
| pending.last_error = 'PAYMENT_FAILED'; | ||
| logger.error( | ||
| `Community ${community.id}: Withdraw failed after ${pending.attempts} attempts, amount ${pending.amount} sats` | ||
| ); | ||
| } | ||
|
|
||
| if ( | ||
| process.env.PAYMENT_ATTEMPTS !== undefined && | ||
| pending.attempts === parseInt(process.env.PAYMENT_ATTEMPTS) | ||
| pending.attempts >= parseInt(process.env.PAYMENT_ATTEMPTS) | ||
| ) { | ||
| await bot.telegram.sendMessage( | ||
| user.tg_id, | ||
|
|
@@ -185,9 +231,6 @@ export const attemptCommunitiesPendingPayments = async (bot: Telegraf<CommunityC | |
| }) | ||
| ); | ||
| } | ||
| logger.error( | ||
| `Community ${community.id}: Withdraw failed after ${pending.attempts} attempts, amount ${pending.amount} sats` | ||
| ); | ||
| } | ||
| } catch (error) { | ||
| logger.error(`attemptCommunitiesPendingPayments catch error: ${error}`); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.