SwapApp es un modulo DeFi educativo/prototipo sobre Foundry. El objetivo es simplificar operaciones de swap y provision de liquidez desde una entrada simple en USDC, con foco en integracion futura dentro de Zum Pay.
///SwapApp is an educational/prototype DeFi module built on Foundry. Its goal is to simplify swap operations and liquidity provision from a single USDC entry point, with a future‑focused design aimed at seamless integration into Zum Pay.
- Swap ERC-20 con fee de protocolo y rewards en token de gobernanza.
- Liquidez V2 desde un solo token (
USDC -> swap parcial -> add liquidity). - Estrategia V3 para crear posiciones de liquidez concentrada desde USDC.
- Salida V3 guiada para reducir liquidez, colectar tokens y volver a USDC.
- Helper de quotes V3 para calcular minimos por slippage.
- Helper de rangos V3 para traducir exposicion
Low / Medium / HighatickLower / tickUpper. - Helper de limite de precio V3 para sugerir
sqrtPriceLimitX96y evitar usar0en produccion. - Fork test V3 que valida posicion activa y cobro de fees despues de swaps.
- Runbook para prueba real controlada en Arbitrum.
-***/ Current Status ERC‑20 swap with protocol fee and governance‑token rewards.
V2 liquidity from a single token (USDC -> partial swap -> add liquidity).
V3 strategy to create concentrated liquidity positions starting from USDC.
Guided V3 exit to reduce liquidity, collect tokens, and return to USDC.
V3 quote helper to calculate minimum amounts based on slippage.
V3 range helper to translate exposure profiles Low / Medium / High into tickLower / tickUpper.
V3 price‑limit helper to suggest sqrtPriceLimitX96 and avoid using 0 in production.
V3 fork test validating active position and fee collection after swaps.
Runbook for controlled real‑world testing on Arbitrum.
El usuario no deberia tener que entender rutas, ticks, fee tiers o liquidez concentrada para operar.
***Product Vision Users shouldn’t need to understand routes, ticks, fee tiers, or concentrated liquidity in order to operate.
Flujo buscado:
- Entra con USDC.
- Elige V2 simple o V3 concentrada.
- En V3 elige perfil de exposicion:
Low,MediumoHigh. - La app calcula quote, rango, minimos y limite de precio.
- El usuario firma una operacion con condiciones claras.
*** Product Vision Users shouldn’t need to understand routes, ticks, fee tiers, or concentrated liquidity to operate.
Target flow:
User enters with USDC.
Chooses simple V2 or concentrated V3.
In V3, selects an exposure profile: Low, Medium, or High.
The app calculates quotes, ranges, minimums, and price limits.
The user signs a single transaction with clear conditions.
- src/swappApp.sol: swaps, rewards, add/remove liquidity V2.
- src/GovernanceToken.sol: token GOV usado en rewards.
- src/V3LiquidityStrategy.sol: ejecuta el flujo V3 desde USDC.
- src/V3QuoteHelper.sol: estima salida esperada y minimos por slippage.
- src/V3RangeHelper.sol: calcula rangos por perfil de exposicion.
- src/V3PriceLimitHelper.sol: calcula
sqrtPriceLimitX96sugerido. - src/libraries/TickMath.sol: matematica V3 para convertir tick a sqrt price.
- .env.example: variables no sensibles y direcciones criticas.
- script/CheckBalances.s.sol: consulta balances de ETH/USDC/WETH.
- ops/REAL_TEST_RUNBOOK.md: checklist y bitacora para prueba real.
SwappApp y V3LiquidityStrategy tienen treasury configurado por separado. Para esta etapa, la regla operativa es deployar ambos usando la misma address de treasury.
Esto mantiene la contabilidad simple:
SwappApp.treasury: fees de swaps y salida guiada V2.V3LiquidityStrategy.treasury: fee del 1% en salida V3.- Ambos deben apuntar al mismo destino operativo.
amountOutMinSwap: revierte si el swap recibe menos de lo aceptado.amountUSDCMinMint/amountTokenMinMint: revierte si el mint V3 queda fuera de minimos.sqrtPriceLimitX96: limita el precio cruzado por el swap V3.deadline: evita ejecucion tardia.V3QuoteHelper: sugiere minimos desde quote + slippage.V3RangeHelper: evita rangos/ticks incoherentes.V3PriceLimitHelper: sugiere limite de precio para no usar0en produccion.- Salida V2 cobra
3.5%sobre el USDC total de salida y lo envia atreasury. - Salida V3 cobra
1%sobre el USDC total de salida y lo envia atreasury.
Nota: para ejecucion real sensible, conviene sumar RPC protegido/MEV protection desde la wallet o frontend.
Entrada:
- El usuario aprueba USDC al contrato
V3LiquidityStrategy. - El contrato swappea una parte a
tokenOther. - El contrato mintea la posicion V3.
- El NFT queda directamente en la wallet del usuario (
recipient = msg.sender).
Salida guiada:
- El usuario debe aprobar su NFT V3 al contrato
V3LiquidityStrategy. - El contrato llama
decreaseLiquidity(...). - El contrato llama
collect(...)hacia si mismo. - El contrato swappea
tokenOthera USDC. - El contrato cobra
1%de execution/strategy fee sobretotalUSDCOut. - El contrato envia la fee a
treasury. - El contrato devuelve el USDC neto al usuario.
- Si
burnIfEmpty = truey la liquidez queda en cero, intenta quemar el NFT.
Owner/treasury no pueden retirar liquidez del usuario porque el NFT pertenece al usuario. La estrategia solo puede operar el NFT si el usuario la aprueba.
Entrada:
- El usuario aprueba USDC al contrato
SwappApp. - El contrato swappea una parte a
tokenOther. - El contrato agrega liquidez en Uniswap V2.
- Los LP tokens quedan directamente en la wallet del usuario.
Salida guiada:
- El usuario aprueba sus LP tokens V2 al contrato
SwappApp. - El contrato retira la liquidez.
- El contrato swappea
tokenOthera USDC. - El contrato cobra
3.5%de strategy fee sobretotalUSDCOut. - El contrato envia la fee a
treasury. - El contrato devuelve el USDC neto al usuario.
cp .env.example .envEditar .env localmente:
ARBITRUM_RPC_URL=https://arbitrum-one-rpc.publicnode.com
WATCH_WALLET=0xYourWallet.env no debe subirse al repo.
forge build --sizesforge test -vv --match-contract SwapAppTest
forge test -vv --match-contract V3LiquidityStrategyTest
forge test -vv --match-contract V3PriceLimitHelperTest
forge test -vv --match-contract V3QuoteHelperTest
forge test -vv --match-contract V3RangeHelperTest╭------------------------------+------------------+------------------+----------------+-----------------╮ | File | % Lines | % Statements | % Branches | % Funcs | +=======================================================================================================+ | src/mocks/MockAggregator.sol | 100.00% (14/14) | 100.00% (10/10) | 100.00% (0/0) | 100.00% (4/4) | |------------------------------+------------------+------------------+----------------+-----------------| | src/mocks/MockERC20.sol | 100.00% (6/6) | 100.00% (3/3) | 100.00% (0/0) | 100.00% (3/3) | |------------------------------+------------------+------------------+----------------+-----------------| | src/presale.sol | 98.96% (95/96) | 98.99% (98/99) | 82.93% (34/41) | 100.00% (12/12) | |------------------------------+------------------+------------------+----------------+-----------------| | test/Presale.t.sol | 100.00% (4/4) | 100.00% (2/2) | 100.00% (0/0) | 100.00% (2/2) | |------------------------------+------------------+------------------+----------------+-----------------| | Total | 99.17% (119/120) | 99.12% (113/114) | 82.93% (34/41) | 100.00% (21/21) | ╰------------------------------+------------------+------------------+----------------+-----------------╯
ARBITRUM_RPC_URL=https://arbitrum-one-rpc.publicnode.com forge test -vv --match-contract SwapAppForkArbitrumTestTest puntual de posicion V3 activa + fees:
ARBITRUM_RPC_URL=https://arbitrum-one-rpc.publicnode.com forge test -vv --match-test test_fork_v3_position_remains_active_and_collects_fees_after_swapssource .env
forge script script/CheckBalances.s.sol:CheckBalances --rpc-url "$ARBITRUM_RPC_URL"forge fmt
forge fmt --checkUsar ops/REAL_TEST_RUNBOOK.md.
Primer objetivo:
- monto chico de USDC
- Arbitrum One
- V3 con exposicion
Low - slippage definido
sqrtPriceLimitX96sugerido por helper- registrar balances, tx hashes, gas, refunds y fees
- Revisar git status y confirmar que no queden cambios sin entender.
- Ejecutar unit tests y fork test principal.
- Si se va a probar real: completar
.env, correr balances y seguir el runbook. - Antes de integrar en Zum Pay: decidir si se deploya este modulo como contratos separados o si se empaqueta como modulo interno.
Este repositorio es educativo/prototipo. Antes de produccion:
- Auditoria externa.
- Ownership seguro (multisig/timelock si aplica).
- RPC protegido para ejecuciones sensibles.
- Politica de slippage/deadline por defecto.
- Monitoreo de balances, posiciones, refunds y fees.
- UX clara: esto no es renta fija ni rendimiento garantizado.