-
Notifications
You must be signed in to change notification settings - Fork 44
π‘οΈ SECURITY: Implement advanced slippage protection and MEV defense #80
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
Open
diretjohn
wants to merge
1
commit into
Stellar-Tools:main
Choose a base branch
from
diretjohn:fix/enhanced-slippage-protection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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 |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ import { | |
| } from "@stellar/stellar-sdk"; | ||
| import { getSigningKeypair, signTransaction } from "./stellar"; | ||
| import { buildPathPaymentTransaction } from "../utils/buildTransaction"; | ||
| import { SlippageProtectionManager, validateSlippage } from "./slippageProtection"; | ||
|
|
||
| export type StellarAssetInput = | ||
| | { type: "native" } | ||
|
|
@@ -27,6 +28,8 @@ export interface QuoteSwapParams { | |
|
|
||
| export interface SwapBestRouteParams extends QuoteSwapParams { | ||
| slippageBps?: number; | ||
| enableSlippageProtection?: boolean; // π‘οΈ NEW: Enable advanced slippage protection | ||
| maxPriceImpactBps?: number; // π‘οΈ NEW: Maximum acceptable price impact | ||
| } | ||
|
|
||
| export interface HorizonPathRecord { | ||
|
|
@@ -56,6 +59,10 @@ export interface SwapBestRouteResult { | |
| sendAmount: string; | ||
| destAmount: string; | ||
| path: StellarAssetInput[]; | ||
| // π‘οΈ NEW: Enhanced result information | ||
| actualSlippageBps?: number; | ||
| priceImpactBps?: number; | ||
| protectionWarnings?: string[]; | ||
| } | ||
|
|
||
| export interface DexClientConfig { | ||
|
|
@@ -157,21 +164,34 @@ export function calculateSwapBounds( | |
| mode: RouteMode, | ||
| slippageBps: number = DEFAULT_SLIPPAGE_BPS | ||
| ): { sendMax?: string; destMin?: string } { | ||
| // π‘οΈ SECURITY: Enhanced slippage validation | ||
| validateSlippage(slippageBps, 1000); // Max 10% slippage allowed | ||
|
|
||
| if (!Number.isInteger(slippageBps) || slippageBps < 0) { | ||
| throw new Error("slippageBps must be a non-negative integer"); | ||
| throw new Error("π‘οΈ slippageBps must be a non-negative integer"); | ||
| } | ||
|
|
||
| const slippage = new Big(slippageBps).div(10000); | ||
|
|
||
| if (mode === "strict-send") { | ||
| return { | ||
| destMin: formatStellarAmount(new Big(quote.destAmount).mul(new Big(1).minus(slippage))), | ||
| }; | ||
| const destMin = formatStellarAmount(new Big(quote.destAmount).mul(new Big(1).minus(slippage))); | ||
|
|
||
| // π‘οΈ SECURITY: Validate minimum output is reasonable | ||
| if (new Big(destMin).lte(0)) { | ||
| throw new Error("π‘οΈ Calculated minimum output is zero or negative - slippage too high"); | ||
| } | ||
|
|
||
| return { destMin }; | ||
| } | ||
|
|
||
| return { | ||
| sendMax: formatStellarAmount(new Big(quote.sendAmount).mul(new Big(1).plus(slippage))), | ||
| }; | ||
| const sendMax = formatStellarAmount(new Big(quote.sendAmount).mul(new Big(1).plus(slippage))); | ||
|
|
||
| // π‘οΈ SECURITY: Validate maximum input is reasonable | ||
| if (new Big(sendMax).gte(new Big(quote.sendAmount).mul(2))) { | ||
| throw new Error("π‘οΈ Calculated maximum input is unreasonably high - check slippage settings"); | ||
| } | ||
|
|
||
| return { sendMax }; | ||
| } | ||
|
|
||
| export async function quoteSwap( | ||
|
|
@@ -214,6 +234,10 @@ export async function swapBestRoute( | |
| validateQuoteParams(params); | ||
| validateQuoteLimit(params.limit); | ||
|
|
||
| // π‘οΈ SECURITY: Enhanced slippage validation with protection | ||
| const requestedSlippageBps = params.slippageBps ?? DEFAULT_SLIPPAGE_BPS; | ||
| validateSlippage(requestedSlippageBps, 1000); // Max 10% slippage | ||
|
|
||
| getSigningKeypair(client.publicKey); | ||
|
|
||
| const destination = params.destination ?? client.publicKey; | ||
|
|
@@ -223,7 +247,55 @@ export async function swapBestRoute( | |
| const bestQuote = quotes[0]; | ||
|
|
||
| if (!bestQuote) { | ||
| throw new Error("No route available for the requested swap"); | ||
| throw new Error("π‘οΈ No route available for the requested swap"); | ||
| } | ||
|
|
||
| // π‘οΈ SECURITY: Apply slippage protection if enabled | ||
| let finalSlippageBps = requestedSlippageBps; | ||
| let protectionWarnings: string[] = []; | ||
| let priceImpactBps = 0; | ||
|
|
||
| if (params.enableSlippageProtection !== false) { // Default to enabled | ||
| const slippageProtection = new SlippageProtectionManager({ | ||
| maxSlippageBps: 1000, // 10% absolute maximum | ||
| priceImpactWarningThreshold: params.maxPriceImpactBps ?? 200, // 2% default warning threshold | ||
| }); | ||
|
|
||
| const tradeAmount = params.mode === "strict-send" ? params.sendAmount! : bestQuote.sendAmount; | ||
|
|
||
| const protection = slippageProtection.analyzeSlippageProtection( | ||
| bestQuote, | ||
| requestedSlippageBps, | ||
| tradeAmount, | ||
| params.sendAsset, | ||
| params.destAsset | ||
| ); | ||
|
|
||
| if (!protection.shouldProceed) { | ||
| throw new Error( | ||
| `π‘οΈ Trade blocked by slippage protection:\n` + | ||
| `${protection.warnings.join('\n')}\n` + | ||
| `Consider reducing trade size or adjusting parameters.` | ||
| ); | ||
| } | ||
|
|
||
| finalSlippageBps = protection.adjustedSlippageBps; | ||
| protectionWarnings = protection.warnings; | ||
| priceImpactBps = protection.priceImpact.priceImpactBps; | ||
|
|
||
| // Log protection warnings | ||
| if (protectionWarnings.length > 0) { | ||
| console.warn("π‘οΈ Slippage Protection Warnings:"); | ||
| protectionWarnings.forEach(warning => console.warn(` ${warning}`)); | ||
| } | ||
|
|
||
| // Additional price impact check | ||
| if (params.maxPriceImpactBps && priceImpactBps > params.maxPriceImpactBps) { | ||
|
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. P1: Prompt for AI agents |
||
| throw new Error( | ||
| `π‘οΈ Price impact ${priceImpactBps / 100}% exceeds maximum allowed ${params.maxPriceImpactBps / 100}%.\n` + | ||
| `${protection.priceImpact.recommendation}` | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| const createServer = | ||
|
|
@@ -234,7 +306,7 @@ export async function swapBestRoute( | |
| const { sendMax, destMin } = calculateSwapBounds( | ||
| bestQuote, | ||
| params.mode, | ||
| params.slippageBps ?? DEFAULT_SLIPPAGE_BPS | ||
| finalSlippageBps // Use protected slippage | ||
| ); | ||
|
|
||
| const transaction = buildPathPaymentTransaction(sourceAccount, { | ||
|
|
@@ -268,6 +340,10 @@ export async function swapBestRoute( | |
| sendAmount: params.mode === "strict-send" ? params.sendAmount! : bestQuote.sendAmount, | ||
| destAmount: params.mode === "strict-receive" ? params.destAmount! : bestQuote.destAmount, | ||
| path: bestQuote.path, | ||
| // π‘οΈ NEW: Include protection information | ||
| actualSlippageBps: finalSlippageBps, | ||
| priceImpactBps: priceImpactBps || undefined, | ||
| protectionWarnings: protectionWarnings.length > 0 ? protectionWarnings : undefined, | ||
| }; | ||
| } | ||
|
|
||
|
|
||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Dead/unreachable guard: the 2x maximum-input check can never trigger because slippage is capped at 10%.
Prompt for AI agents