- Update dbis_core, cross-chain-pmm-lps, explorer-monorepo, metamask-integration, pr-workspace/chains - Omit embedded publish git dirs and empty placeholders from index Made-with: Cursor
17 KiB
Economics flows — inputs, outputs, flash, collateral, repayment, profit
Percent units match the toolkit (economics-toolkit calc): grossPct / flashFeePct are expressed as percent of notional (e.g. 0.29 = 0.29%), not decimal fractions.
Single-transaction PMM swap (no flash)
| Description | |
|---|---|
| Inputs | tokenIn balance + allowance to DODOPMMIntegration; amountIn; gas (native token). |
| Outputs | tokenOut received from pool (querySellBase / querySellQuote); any dust stays in wallet. |
| Flash loan | None. |
| Collateral | None (spot swap: you own tokenIn). |
| Repayments | None beyond pool fee / slippage inside the swap (no third-party loan). |
| Profit | amountOut - amountIn in value terms (same units or mark-to-market), minus gas. Toolkit implied gross %: ((\text{amountOut}/\text{amountIn} - 1) \times 100) before gas. |
Flash-assisted path (borrow → trade → repay in one tx)
| Description | |
|---|---|
| Inputs | Flash provider callback; planned amountIn of asset to borrow; encoded inner actions; gas. |
| Flash loan | Principal B from provider (e.g. Aave/Balancer/contract-specific); fee B × flashFeePct / 100 (toolkit: flashFeePct). |
| Collateral | None for the borrowed asset in the same tx (loan is repaid atomically). Smart contract may hold temporary balances during the callback. |
| Repayments | B + fee (and any protocol-specific premium) to the flash provider before the outer tx ends; revert if underpaid. |
| Outputs | Whatever the inner strategy leaves in the executing contract/wallet after repay (often zero net token profit if pure arb). |
| Profit | For end-user: gross ≈ value gained on the path; net ≈ gross − flashFeePct − gasPctOfNotional − other buckets (evaluateEconomics residual). |
Toolkit calc (budgeting only)
| Field | Role |
|---|---|
| Inputs | grossPct, flashFeePct, optional gasPctOfNotional, liquidityPct, minProfitPct. |
| Outputs | netAfterFlashPct, bucketsTotalPct, residualPct, passesResidual, sensitivity[]. |
| Flash loan | Modeled only as flashFeePct of notional (not principal size). |
| Collateral | Not modeled (add explicit rows in your own sheet if you use margin elsewhere). |
| Repayments | Implicit: flash fee is the “repay overhead” in % terms. |
| Profit | residualPct after flash and buckets; must be ≥ minProfitPct for passesResidual. |
Toolkit path-check (Chain 138 PMM quote + gate)
| Field | Role |
|---|---|
| Inputs | --rpc, --pool, --token-in, --amount-in, --trader, economics flags (--flash, --gas, --liquidity, …). |
| Outputs | amountOut, impliedGrossPct, full economics object, passesEconomicsGate. |
| Flash loan | Not executed; flash is a budget line only. |
| Collateral | N/A (quote-only). |
| Repayments | N/A. |
| Profit | Implied from quote vs amountIn; gate uses same economics as calc. |
Cross-check: your bucket example
| Line item | Example % (of notional) |
|---|---|
| Gross (from path / quote) | 0.29 |
| Flash fee | 0.09 |
| Net after flash | 0.20 |
| Gas bucket | 0.10 |
| Liquidity bucket | 0.01 |
| Residual (profit buffer) | 0.09 |
Use: pnpm exec economics-toolkit calc --gross 0.29 --flash 0.09 --gas 0.1 --liquidity 0.01
Numerical tables — wallet liquidity 100, 175, and 250 USDT
Assumptions (illustrative budgeting, not live quotes):
- Wallet liquidity = full notional deployed in one swap path (all-in USDT stable leg).
- Gross = 0.29% of notional (treat as quoted edge before modeled fees).
- Flash fee = 0.09% of flash principal (B) (when a flash is used; see below).
- Gas bucket = 0.10% of notional; Liquidity bucket = 0.01% of notional (same as
calc --gas 0.1 --liquidity 0.01). - Residual % = 0.29 − 0.09 − 0.10 − 0.01 = 0.09% of notional when flash is sized to notional (see flash section for (B = 10×) wallet).
Amounts in USDT (6 dp); small rounding may appear in spreadsheets.
A. Single swap / single path (notional = wallet)
| Wallet (USDT) | Notional (USDT) | Gross @ 0.29% (USDT) | Flash fee @ 0.09% of N (USDT) | Net after flash (USDT) | Gas bucket 0.10% (USDT) | Liq bucket 0.01% (USDT) | Residual profit (USDT) |
|---|---|---|---|---|---|---|---|
| 100 | 100 | 0.290000 | 0.090000 | 0.200000 | 0.100000 | 0.010000 | 0.090000 |
| 175 | 175 | 0.507500 | 0.157500 | 0.350000 | 0.175000 | 0.017500 | 0.157500 |
| 250 | 250 | 0.725000 | 0.225000 | 0.500000 | 0.250000 | 0.025000 | 0.225000 |
Spot swap (no flash): drop the flash column and use Gross − gas − liq only → residual = (0.29% − 0.10% − 0.01%) × N = 0.18% × N → 0.18 / 0.315 / 0.45 USDT respectively.
B. Flash principal (B = 10×) wallet (fee on borrowed amount)
Flash repayment (principal + fee) is in borrowed units; fee cash cost scales with (B).
| Wallet (USDT) | Flash borrow B (USDT) | Flash fee @ 0.09% of B (USDT) |
|---|---|---|
| 100 | 1000 | 0.900000 |
| 175 | 1750 | 1.575000 |
| 250 | 2500 | 2.250000 |
Gross path and gas/liquidity buckets are still often modeled on trade notional or path-specific rules; align (B) with your contract’s actual borrow.
C. Multi-round — linear (R separate full-notional passes, same wallet each time)
Each round uses notional = wallet again; cumulative residual = R × (0.09% × N) with flash-on-N; or R × (0.18% × N) spot-only.
| Wallet (USDT) | Residual / round (USDT) | R = 5 (USDT) | R = 25 (USDT) | R = 100 (USDT) | R = 250 (USDT) |
|---|---|---|---|---|---|
| 100 | 0.090000 | 0.450000 | 2.250000 | 9.000000 | 22.500000 |
| 175 | 0.157500 | 0.787500 | 3.937500 | 15.750000 | 39.375000 |
| 250 | 0.225000 | 1.125000 | 5.625000 | 22.500000 | 56.250000 |
Spot-only linear (0.18% × N per round): multiply the row by 2 (i.e. R × 0.18% × N).
Requires R transactions and R× gas in the real world unless batched.
D. Multi-round — compound (reinvest residual each round, same % on growing balance)
Residual rate (r = 0.09% = 0.0009) per round (flash-on-N model). Ending extra vs start: (N \times ((1+r)^R - 1)).
| Wallet N (USDT) | R = 5 (USDT) | R = 25 (USDT) | R = 100 (USDT) | R = 250 (USDT) |
|---|---|---|---|---|
| 100 | 0.450811 | 2.274469 | 9.413000 | 25.219600 |
| 175 | 0.788919 | 3.980320 | 16.472749 | 44.134300 |
| 250 | 1.127027 | 5.686171 | 23.532499 | 63.049000 |
Compound here assumes each round earns 0.09% on the current balance; real PMM depth and slippage change effective %.
E. One atomic bundle vs many txs (conceptual)
| Pattern | Flash fees | Gas / other |
|---|---|---|
| One tx (flash + swaps + repay) | One 0.09% on borrow (B) (if used) | One gas bucket (often one estimateGas) |
| R txs | R × flash (if each uses flash) or 0 | R × gas; R × failure / MEV exposure between rounds |
F. Collateral (optional lending loop — not the PMM spot path)
If you borrow on margin with collateral (C) in USDT and LTV so borrow = (k \cdot C), repayment is loan + interest, not the flash row above. This toolkit’s calc line does not include interest APR or liquidation; extend your sheet with:
- Collateral in → borrow → swap rounds → repay loan + interest → release collateral.
Use fixed 100 / 175 / 250 USDT (or your own grid) as (C) only in your own risk model; no extra table unless you specify LTV and borrow APR.
G. Real-time gas (replace fixed “gas bucket %” with live quotes)
The toolkit can pull current feeData from each network’s JSON-RPC and estimate tx cost = gasUnits × effectiveGasPrice (legacy gasPrice, else EIP-1559 maxFeePerGas as a conservative bound).
# All configured networks (see packages/economics-toolkit/config/gas-networks.json)
pnpm exec economics-toolkit gas-quote --gas-units 250000
# Subset + optional notional (USDT) to print gas as % of notional (CoinGecko USD for native token)
pnpm exec economics-toolkit gas-quote --chains 1,56,137,138 --gas-units 250000 --notional-usdt 175
# Native-only (no CoinGecko):
ECONOMICS_GAS_SKIP_USD=1 pnpm exec economics-toolkit gas-quote --chains 138 --gas-units 250000
- Networks / RPCs: defaults are public endpoints; override per chain with
ECONOMICS_GAS_RPC_<chainId>(e.g.ECONOMICS_GAS_RPC_1). Chain 138 usesRPC_URL_138when set, else the public FQDN in config. - USD: optional via CoinGecko public
simple/price(rate limits apply). Chain 138 has no default USD mapping for the native unit; useECONOMICS_GAS_SKIP_USD=1or extend config. - gas-units: use your own
estimateGasfrom a simulation (e.g.execdry-run) for accuracy; 250000 is a generic swap-shaped default.
Gas budget vs wallet balance (gas-budget): For a single chain (the RPC you pass), the toolkit can combine eth_getBalance with the same fee heuristic as gas-quote and report how many identical transactions you could afford if you allocated 25%, 50%, 75%, or 100% of the account’s current native balance to gas (floor division; one cost model per run). This does not send transactions. Use an explicit --address, or omit it and set PRIVATE_KEY or ECONOMICS_GAS_BUDGET_PRIVATE_KEY so the deployer EOA is derived (read-only balance fetch).
pnpm exec economics-toolkit gas-budget --rpc $RPC_URL_138 --address 0xYourDeployer
pnpm exec economics-toolkit gas-budget --rpc $RPC_URL_138 --gas-units 300000 # address from PRIVATE_KEY
H. RPC dotenv alignment (operator scripts and economics toolkit)
| Purpose | Primary variables | Notes |
|---|---|---|
| Chain 138 core (deploy, LAN Besu VMID 2101) | RPC_URL_138, CHAIN138_RPC_URL |
Default http://192.168.11.211:8545 via scripts/lib/load-project-env.sh |
| Chain 138 public (frontends, bridges, MetaMask) | RPC_URL_138_PUBLIC |
Prefer HTTPS FQDN; public node VMID 2201 / 192.168.11.221 — do not point read-only indexers at core 211 |
| Token-aggregation service | CHAIN_138_RPC_URL, TOKEN_AGGREGATION_*_RPC_URL, RPC_URL_138 |
Precedence in smom-dbis-138/services/token-aggregation/src/config/chain138-rpc.ts and PMM quote helper |
| Gas quote overrides | ECONOMICS_GAS_RPC_<chainId> |
Per-chain RPC for economics-toolkit gas-quote; chain 138 also respects RPC_URL_138 in gas-realtime.ts |
| Strip CR/LF | All of the above + relay / multichain RPC names | load-project-env.sh strips line endings on these URLs so cast/curl do not break |
Canonical endpoints and FQDNs: docs/04-configuration/RPC_ENDPOINTS_MASTER.md. Master template: .env.master.example.
I. Multi-leg strategy building (collateral toggle, debt/collateral swap, unwind, LP, bridge, …)
Strategies are JSON documents (version: 1) with legs[]. Each leg has a kind (taxonomy for your runbooks), grossPct, optional flash fields, gas/liquidity buckets, fixedCostUsdt, notes, and optional:
| Feature | Purpose |
|---|---|
slippageBps / protocolFeeBps |
Execution / protocol drag (1 bp = 0.01 percentage points subtracted from gross). |
mevDragBps / ilDragBps / liquidationCompetitionBps |
Budget lines for MEV, impermanent loss, and liquidation competition (same bps units). |
derivedFrom |
Linear function of a prior leg’s residualPct, netAfterFlashPct, grossEffectivePct, or bucketsTotalPct (earlier in legs[] only). |
derivedExpr |
Safe arithmetic tree over prior legs (const, ref, add…neg); mutually exclusive with derivedFrom. |
enrichPathCheck / enrichGas |
Hints for strategy enrich to pull implied gross (Chain 138 PMM) and gas % of notional from live RPC. |
exec |
raw calldata or pmm_swap_exact_in for strategy exec-plan (simulation-only; see section J). |
Flash vs base notional: fee is % of borrow (B); set flashNotionalMultiple so (B = \text{baseNotional} \times M). Effective flash as % of base is M × flashFeePct.
Aggregate modes:
| Mode | Meaning |
|---|---|
linear_pct_sum |
Sum each leg’s economics.residualPct × weight (side-by-side budget lines). |
sequential_compound_usd |
Start at baseNotionalUsdt; after each leg multiply by (1 + residualPct/100) then subtract fixedCostUsdt. |
CLI (essentials):
pnpm exec economics-toolkit strategy kinds
pnpm exec economics-toolkit strategy template --out ./my-strategy.json
pnpm exec economics-toolkit strategy validate --file ./my-strategy.json # parse-only (--quiet for batch/CI)
pnpm exec economics-toolkit strategy eval --file packages/economics-toolkit/config/strategy-smoke.json
pnpm exec economics-toolkit strategy eval --file ./my-strategy.json # exit 1 if any leg fails minProfit
pnpm exec economics-toolkit strategy optimize --file ./my-strategy.json --leg open_flash_arb \
--gross-min 0.15 --gross-max 0.45 --step 0.05 --objective max_linear_residual
pnpm exec economics-toolkit strategy optimize-multi --file ./my-strategy.json --dims-file packages/economics-toolkit/config/strategy-optimize-dims.example.json
pnpm exec economics-toolkit strategy optimize-random --file ./my-strategy.json \
--bounds-file packages/economics-toolkit/config/strategy-bounds.example.json --samples 400 --seed 1
pnpm exec economics-toolkit strategy optimize-descent --file ./my-strategy.json \
--bounds-file packages/economics-toolkit/config/strategy-bounds.example.json --rounds 8 --line-steps 12
pnpm exec economics-toolkit strategy enrich --file ./my-strategy.json --rpc $RPC_URL_138
bash scripts/economics/refresh-strategy-from-live.sh ./my-strategy.json
bash scripts/economics/refresh-strategy-from-live.sh --apply ./my-strategy.json
pnpm exec economics-toolkit strategy runbook --file ./my-strategy.json --format md
pnpm exec economics-toolkit strategy exec-plan --file ./my-strategy.json
pnpm exec economics-toolkit strategy exec-plan --file ./my-strategy.json --simulate --rpc $RPC_URL_138 \
--from <EOA> --allowlist packages/economics-toolkit/config/executor-allowlist.example.json
Validation in repo: pnpm run economics:validate runs scripts/validation/validate-economics-strategy-json.sh (also invoked from validate-config-files.sh). Optional JSON Schema check requires pip install check-jsonschema.
Artifacts: strategy-template.json, strategy.schema.json, strategy-smoke.json, strategy-bounds.example.json, strategy-optimize-dims.example.json. Source: strategy-types.ts, strategy-engine.ts, strategy-expr.ts.
Automation vs manual: enrich and refresh-strategy-from-live.sh fill grossPct / gasPctOfNotional when enrichPathCheck / enrichGas are present. Deep AMM IL curves, MEV equilibrium, and liquidation games are not closed-form in the engine—use ilDragBps, mevDragBps, liquidationCompetitionBps, or external models feeding grossPct.
J. Roadmap and repo-wide TODOs
- Toolkit: Optional future work: closed-form IL from pool state; margin APR / LTV as first-class legs (today: extend your own model per section F).
exec-planonly simulates; production sends remaineconomics-toolkit exec --applywith an allowlist. Multi-step EOA flows require one nonce per tx and dependency ordering—exec-planJSON includes asequencingNoteon each step. Largeoptimize-descentruns scale withrounds × bounds × lineGridSteps. - Workspace: Broader deployments and operators:
docs/00-meta/TODOS_CONSOLIDATED.mdand related meta docs.