|
| 1 | +# Batch Ticket Purchase Implementation |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Implemented `buyBatch()` method in the TicketService to allow users to purchase tickets for multiple raffles in a single operation. |
| 6 | + |
| 7 | +## Branch |
| 8 | + |
| 9 | +`feature/batch-ticket-purchase` |
| 10 | + |
| 11 | +## Changes Made |
| 12 | + |
| 13 | +### 1. Type Definitions (`sdk/src/modules/ticket/ticket.types.ts`) |
| 14 | + |
| 15 | +Added new types to support batch purchases: |
| 16 | + |
| 17 | +- `BatchTicketPurchase`: Represents a single purchase in a batch (raffleId + quantity) |
| 18 | +- `BuyBatchParams`: Input parameters for batch purchase (array of purchases + optional memo) |
| 19 | +- `BatchPurchaseResult`: Result for individual raffle purchase (success/failure with details) |
| 20 | +- `BuyBatchResult`: Overall batch operation result with individual results and transaction info |
| 21 | + |
| 22 | +### 2. Service Implementation (`sdk/src/modules/ticket/ticket.service.ts`) |
| 23 | + |
| 24 | +Implemented `buyBatch()` method with the following features: |
| 25 | + |
| 26 | +#### Validation |
| 27 | +- Validates all purchases upfront (raffleId and quantity must be positive integers) |
| 28 | +- Throws immediately if purchases array is empty or any purchase has invalid parameters |
| 29 | + |
| 30 | +#### Simulation Phase |
| 31 | +- Simulates each purchase individually using `simulateReadOnly()` |
| 32 | +- Identifies which purchases are feasible before execution |
| 33 | +- Tracks simulation failures separately from execution failures |
| 34 | + |
| 35 | +#### Execution Phase |
| 36 | +- Executes only purchases that passed simulation |
| 37 | +- Processes purchases sequentially (Soroban limitation - no atomic multi-call) |
| 38 | +- Continues processing even if individual purchases fail |
| 39 | +- Tracks individual success/failure results with error messages |
| 40 | + |
| 41 | +#### Gas Management |
| 42 | +- Pre-filters failed simulations to avoid wasted gas |
| 43 | +- Accumulates fees across all successful transactions |
| 44 | +- Returns total fee paid in the result |
| 45 | + |
| 46 | +#### Error Handling |
| 47 | +- Returns individual success/failure for each raffle |
| 48 | +- Throws only if all purchases fail or validation fails |
| 49 | +- Provides detailed error messages for each failed purchase |
| 50 | +- Handles external contract errors (e.g., token contract rejections) |
| 51 | + |
| 52 | +### 3. Unit Tests (`sdk/src/modules/ticket/ticket.service.spec.ts`) |
| 53 | + |
| 54 | +Added comprehensive test coverage: |
| 55 | + |
| 56 | +- ✅ Successful batch purchase across multiple raffles |
| 57 | +- ✅ Partial failure handling (some succeed, some fail) |
| 58 | +- ✅ Empty purchases array validation |
| 59 | +- ✅ Invalid purchase parameter validation |
| 60 | +- ✅ All purchases fail simulation |
| 61 | +- ✅ Memo propagation to individual purchases |
| 62 | + |
| 63 | +### 4. Example (`sdk/examples/buy-tickets-batch.ts`) |
| 64 | + |
| 65 | +Created a complete example demonstrating: |
| 66 | + |
| 67 | +- Environment variable configuration |
| 68 | +- Pre-purchase raffle verification |
| 69 | +- Batch purchase execution |
| 70 | +- Result display with success/failure breakdown |
| 71 | +- Post-purchase ticket listing |
| 72 | + |
| 73 | +### 5. Documentation (`sdk/src/modules/ticket/README.md`) |
| 74 | + |
| 75 | +Updated README with: |
| 76 | + |
| 77 | +- Usage examples for batch purchases |
| 78 | +- Complete API documentation for `buyBatch()` |
| 79 | +- Transaction atomicity explanation |
| 80 | +- Gas management details |
| 81 | +- Error handling behavior |
| 82 | +- Implementation notes about Soroban limitations |
| 83 | + |
| 84 | +## Key Design Decisions |
| 85 | + |
| 86 | +### Sequential Execution vs Atomic Transactions |
| 87 | + |
| 88 | +**Decision**: Execute purchases sequentially rather than attempting atomic multi-call. |
| 89 | + |
| 90 | +**Rationale**: |
| 91 | +- Soroban doesn't support true atomic multi-call in a single transaction |
| 92 | +- Sequential execution allows partial success (some purchases succeed even if others fail) |
| 93 | +- Users get immediate feedback on which purchases succeeded/failed |
| 94 | +- Application-level rollback logic can be implemented if atomicity is critical |
| 95 | + |
| 96 | +### Individual Simulation |
| 97 | + |
| 98 | +**Decision**: Simulate each purchase individually before execution. |
| 99 | + |
| 100 | +**Rationale**: |
| 101 | +- Identifies infeasible purchases early (closed raffles, insufficient tickets, etc.) |
| 102 | +- Avoids wasting gas on purchases that will fail |
| 103 | +- Provides better error messages for failed simulations |
| 104 | +- Allows filtering out bad purchases before execution |
| 105 | + |
| 106 | +### Partial Failure Handling |
| 107 | + |
| 108 | +**Decision**: Continue processing even if some purchases fail. |
| 109 | + |
| 110 | +**Rationale**: |
| 111 | +- Maximizes successful purchases in a batch |
| 112 | +- Users don't lose all purchases due to one failure |
| 113 | +- Individual results allow users to retry only failed purchases |
| 114 | +- Better user experience for large batches |
| 115 | + |
| 116 | +### Gas Budget Management |
| 117 | + |
| 118 | +**Decision**: Pre-validate and filter, accumulate fees across transactions. |
| 119 | + |
| 120 | +**Rationale**: |
| 121 | +- Simulation filtering reduces wasted gas |
| 122 | +- Fee accumulation provides total cost visibility |
| 123 | +- Users can estimate costs before execution |
| 124 | +- Supports large batches without hitting gas limits per transaction |
| 125 | + |
| 126 | +## API Usage |
| 127 | + |
| 128 | +```typescript |
| 129 | +// Basic batch purchase |
| 130 | +const result = await ticketService.buyBatch({ |
| 131 | + purchases: [ |
| 132 | + { raffleId: 1, quantity: 3 }, |
| 133 | + { raffleId: 2, quantity: 5 }, |
| 134 | + { raffleId: 3, quantity: 2 }, |
| 135 | + ], |
| 136 | +}); |
| 137 | + |
| 138 | +// With memo for tracking |
| 139 | +const result = await ticketService.buyBatch({ |
| 140 | + purchases: [ |
| 141 | + { raffleId: 1, quantity: 3 }, |
| 142 | + { raffleId: 2, quantity: 5 }, |
| 143 | + ], |
| 144 | + memo: { type: 'text', value: 'Batch purchase' }, |
| 145 | +}); |
| 146 | + |
| 147 | +// Check results |
| 148 | +result.results.forEach((r) => { |
| 149 | + if (r.success) { |
| 150 | + console.log(`Raffle ${r.raffleId}: ${r.ticketIds.join(', ')}`); |
| 151 | + } else { |
| 152 | + console.log(`Raffle ${r.raffleId} failed: ${r.error}`); |
| 153 | + } |
| 154 | +}); |
| 155 | +``` |
| 156 | + |
| 157 | +## Testing |
| 158 | + |
| 159 | +Run tests with: |
| 160 | +```bash |
| 161 | +cd sdk |
| 162 | +pnpm install |
| 163 | +pnpm test ticket.service.spec.ts |
| 164 | +``` |
| 165 | + |
| 166 | +Run example with: |
| 167 | +```bash |
| 168 | +TIKKA_NETWORK=testnet \ |
| 169 | +TIKKA_PUBLIC_KEY=G... \ |
| 170 | +TIKKA_RAFFLE_IDS=1,2,3 \ |
| 171 | +TIKKA_QUANTITIES=5,3,2 \ |
| 172 | +npx ts-node examples/buy-tickets-batch.ts |
| 173 | +``` |
| 174 | + |
| 175 | +## Future Enhancements |
| 176 | + |
| 177 | +1. **Contract-Level Batch Support**: If the Soroban contract adds native batch purchase support, update to use atomic transactions |
| 178 | +2. **Parallel Execution**: Explore parallel transaction submission if Soroban supports it |
| 179 | +3. **Retry Logic**: Add automatic retry for transient failures |
| 180 | +4. **Gas Estimation**: Provide upfront gas estimation for entire batch |
| 181 | +5. **Transaction Bundling**: Investigate transaction bundling strategies for better atomicity |
| 182 | + |
| 183 | +## Notes |
| 184 | + |
| 185 | +- Each purchase in a batch is a separate transaction |
| 186 | +- Purchases are not atomic - some can succeed while others fail |
| 187 | +- Failed simulations don't consume gas |
| 188 | +- Failed executions do consume gas but are tracked in results |
| 189 | +- Memo is applied to all transactions in the batch |
| 190 | +- Total fee is accumulated across all successful transactions |
| 191 | + |
| 192 | +## Commit |
| 193 | + |
| 194 | +``` |
| 195 | +feat: add batch ticket purchase functionality |
| 196 | +
|
| 197 | +- Add buyBatch method to TicketService for purchasing tickets across multiple raffles |
| 198 | +- Implement individual simulation for each purchase to check feasibility |
| 199 | +- Handle partial failures gracefully with individual success/failure results |
| 200 | +- Manage gas budget by pre-validating and filtering failed simulations |
| 201 | +- Add comprehensive types: BuyBatchParams, BuyBatchResult, BatchPurchaseResult |
| 202 | +- Add unit tests covering success, partial failure, and error cases |
| 203 | +- Add buy-tickets-batch.ts example demonstrating batch purchase usage |
| 204 | +- Update README with detailed documentation on batch purchase behavior |
| 205 | +- Note: Soroban doesn't support atomic multi-call, purchases execute sequentially |
| 206 | +``` |
0 commit comments