-
Notifications
You must be signed in to change notification settings - Fork 463
feat: simulation before sending order #2774
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
mgrabina
merged 2 commits into
aave:feat/activate-l2s-cow-coll-swap
from
carlos-cow:carlos/simulation
Nov 21, 2025
+277
−0
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
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
229 changes: 229 additions & 0 deletions
229
src/components/transactions/Swap/helpers/cow/simulation.helpers.ts
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,229 @@ | ||
| import { | ||
| encodeAbiParameters, | ||
| erc20Abi, | ||
| encodeFunctionData, | ||
| keccak256, | ||
| toHex, | ||
| } from 'viem'; | ||
| import { getPublicClient } from 'wagmi/actions'; | ||
|
|
||
| import { wagmiConfig } from 'src/ui-config/wagmiConfig'; | ||
|
|
||
| const MULTICALL3_ADDRESS = '0xcA11bde05977b3631167028862bE2a173976CA11'; | ||
| const MULTICALL3_AGGREGATE3_ABI = [ | ||
| { | ||
| inputs: [ | ||
| { | ||
| components: [ | ||
| { internalType: 'address', name: 'target', type: 'address' }, | ||
| { internalType: 'bool', name: 'allowFailure', type: 'bool' }, | ||
| { internalType: 'bytes', name: 'callData', type: 'bytes' }, | ||
| ], | ||
| internalType: 'struct IMulticall3.Call3[]', | ||
| name: 'calls', | ||
| type: 'tuple[]', | ||
| }, | ||
| ], | ||
| name: 'aggregate3', | ||
| outputs: [ | ||
| { | ||
| components: [ | ||
| { internalType: 'bool', name: 'success', type: 'bool' }, | ||
| { internalType: 'bytes', name: 'returnData', type: 'bytes' }, | ||
| ], | ||
| internalType: 'struct IMulticall3.Result[]', | ||
| name: 'returnData', | ||
| type: 'tuple[]', | ||
| }, | ||
| ], | ||
| stateMutability: 'payable', | ||
| type: 'function', | ||
| }, | ||
| ] as const; | ||
|
|
||
| type HookDefinition = { | ||
| target?: string; | ||
| callData?: string; | ||
| gasLimit?: string | number; | ||
| }; | ||
|
|
||
| type FlashloanMetadata = { | ||
| amount?: string; | ||
| token?: string; | ||
| protocolAdapter?: string; | ||
| receiver?: string; | ||
| }; | ||
|
|
||
| type OrderSettlementContext = { | ||
| receiver?: string; | ||
| buyToken?: string; | ||
| buyAmount?: bigint; | ||
| }; | ||
|
|
||
| const DEFAULT_BALANCE_SLOT_CANDIDATES = [0n, 1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n, 11n, 12n]; | ||
|
|
||
| const getBalanceSlotKeys = (owner: string, slotCandidates = DEFAULT_BALANCE_SLOT_CANDIDATES) => { | ||
| return slotCandidates.map((slot) => { | ||
| const encoded = encodeAbiParameters( | ||
| [{ type: 'address' }, { type: 'uint256' }], | ||
| [owner as `0x${string}`, slot] | ||
| ); | ||
| return keccak256(encoded); | ||
| }); | ||
| }; | ||
|
|
||
| const buildBalanceOverride = async ({ | ||
| chainId, | ||
| token, | ||
| recipient, | ||
| amount, | ||
| }: { | ||
| chainId: number; | ||
| token?: string; | ||
| recipient?: string; | ||
| amount?: bigint; | ||
| }) => { | ||
| const normalizedToken = token as `0x${string}` | undefined; | ||
| const normalizedRecipient = recipient as `0x${string}` | undefined; | ||
| if (!normalizedToken || !normalizedRecipient || amount === undefined) return undefined; | ||
|
|
||
| const publicClient = getPublicClient(wagmiConfig, { chainId }); | ||
| if (!publicClient) return undefined; | ||
|
|
||
| let currentBalance = 0n; | ||
| try { | ||
| currentBalance = await publicClient.readContract({ | ||
| address: normalizedToken, | ||
| functionName: 'balanceOf', | ||
| args: [normalizedRecipient], | ||
| abi: erc20Abi, | ||
| }); | ||
| } catch (error) { | ||
| console.warn('[CoW][CollateralSwap] Could not read current balance for state override', error); | ||
| } | ||
|
|
||
| const updatedBalance = currentBalance + amount; | ||
| const balanceSlots = getBalanceSlotKeys(normalizedRecipient); | ||
|
|
||
| const stateDiff: Record<string, string> = {}; | ||
| balanceSlots.forEach((slot) => { | ||
| stateDiff[slot] = toHex(updatedBalance, { size: 32 }); | ||
| }); | ||
|
|
||
| return { [normalizedToken]: { stateDiff } }; | ||
| }; | ||
|
|
||
| const mergeOverrides = (...overrides: (Record<string, { stateDiff: Record<string, string> }> | undefined)[]) => { | ||
| const merged: Record<string, { stateDiff: Record<string, string> }> = {}; | ||
| overrides.forEach((override) => { | ||
| if (!override) return; | ||
| Object.entries(override).forEach(([addr, overrideVal]) => { | ||
| if (!merged[addr]) { | ||
| merged[addr] = { stateDiff: {} }; | ||
| } | ||
| merged[addr].stateDiff = { ...merged[addr].stateDiff, ...overrideVal.stateDiff }; | ||
| }); | ||
| }); | ||
| return Object.keys(merged).length ? merged : undefined; | ||
| }; | ||
|
|
||
| export const simulateCollateralSwapPreHook = async ({ | ||
| chainId, | ||
| from, | ||
| preHook, | ||
| flashloan, | ||
| postHook, | ||
| settlementContext, | ||
| }: { | ||
| chainId: number; | ||
| from?: `0x${string}`; | ||
| preHook?: HookDefinition; | ||
| flashloan?: FlashloanMetadata; | ||
| postHook?: HookDefinition; | ||
| settlementContext?: OrderSettlementContext; | ||
| }) => { | ||
| const caller = from; | ||
|
|
||
| if (!caller || !preHook?.target || !preHook?.callData) { | ||
| console.log('[CoW][CollateralSwap] Skipping preHook simulation, missing data'); | ||
| return false; | ||
| } | ||
|
|
||
| const publicClient = getPublicClient(wagmiConfig, { chainId }); | ||
| if (!publicClient) { | ||
| console.warn('[CoW][CollateralSwap] No public client available for simulation'); | ||
| return; | ||
| } | ||
|
|
||
| const flashloanOverride = await buildBalanceOverride({ | ||
| chainId, | ||
| token: flashloan?.token, | ||
| recipient: flashloan?.protocolAdapter ?? flashloan?.receiver, | ||
| amount: flashloan?.amount ? BigInt(flashloan.amount) : undefined, | ||
| }); | ||
|
|
||
| const settlementOverride = await buildBalanceOverride({ | ||
| chainId, | ||
| token: settlementContext?.buyToken, | ||
| recipient: settlementContext?.receiver, | ||
| amount: settlementContext?.buyAmount, | ||
| }); | ||
|
|
||
| const encodedPreHook = { | ||
| from: caller, | ||
| to: preHook.target as `0x${string}`, | ||
| input: preHook.callData as `0x${string}`, | ||
| gas: preHook.gasLimit ? toHex(BigInt(preHook.gasLimit)) : undefined, | ||
| }; | ||
|
|
||
| const encodedPostHook = | ||
| postHook?.target && postHook?.callData | ||
| ? { | ||
| from: caller, | ||
| to: postHook.target as `0x${string}`, | ||
| input: postHook.callData as `0x${string}`, | ||
| gas: postHook?.gasLimit !== undefined ? toHex(BigInt(postHook.gasLimit)) : undefined, | ||
| } | ||
| : undefined; | ||
|
|
||
| const callsSequence = [{ ...encodedPreHook, label: 'preHook' }, ...(encodedPostHook ? [{ ...encodedPostHook, label: 'postHook' }] : [])]; | ||
|
|
||
| const aggregateData = encodeFunctionData({ | ||
| abi: MULTICALL3_AGGREGATE3_ABI, | ||
| functionName: 'aggregate3', | ||
| args: [ | ||
| callsSequence.map((c) => ({ | ||
| target: c.to as `0x${string}`, | ||
| allowFailure: true, | ||
| callData: (c as any).input ?? c.data, | ||
| })), | ||
| ], | ||
| }); | ||
|
|
||
| const stateOverrides = mergeOverrides(flashloanOverride, settlementOverride); | ||
|
|
||
| const blockStateCall = { | ||
| calls: [{ from, to: MULTICALL3_ADDRESS as `0x${string}`, input: aggregateData, label: 'multicall' }], | ||
| transactions: [{ from, to: MULTICALL3_ADDRESS as `0x${string}`, data: aggregateData }], | ||
| ...(stateOverrides ? { stateOverrides } : {}), | ||
| }; | ||
|
|
||
| const simulationPayload = { | ||
| parentBlock: 'latest', | ||
| blockStateCalls: [blockStateCall], | ||
| }; | ||
|
|
||
| console.log('[CoW][CollateralSwap] PreHook simulation payload', simulationPayload); | ||
|
|
||
| try { | ||
| const result = await publicClient.request({ | ||
| method: 'eth_simulateV1', | ||
| params: [simulationPayload] as unknown[], | ||
| }); | ||
| console.log('[CoW][CollateralSwap] PreHook simulation result', result); | ||
| return true; | ||
| } catch (error) { | ||
| console.error('[CoW][CollateralSwap] PreHook simulation failed', error); | ||
| return false; | ||
| } | ||
| }; | ||
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.
The new eth_simulateV1 check never surfaces failures: the multicall is constructed with
allowFailure: true(line 197), and in the try block the result is only logged before unconditionally returningtrue(lines 220-224). Because aggregate3 reports per-call failures via itssuccessflag instead of throwing whenallowFailureis true, any reverting pre/post hook will still return success here and the code proceeds to post the order even in simulation-only mode. This defeats the safety gate the simulation was meant to provide and lets invalid hook sequences be sent downstream.Useful? React with 👍 / 👎.