Merge pull request #73 from propeller-heads/router/tnl/ENG-4253-usv4-integration

feat: UniswapV4 integration test and fixes
This commit is contained in:
Tamara
2025-02-20 12:36:46 -05:00
committed by GitHub
10 changed files with 208 additions and 160 deletions

View File

@@ -39,7 +39,6 @@ contract UniswapV4Executor is IExecutor, V4Router {
(
address tokenIn,
address tokenOut,
uint256 amountOutMin,
bool zeroForOne,
address callbackExecutor,
bytes4 callbackSelector,
@@ -68,12 +67,12 @@ contract UniswapV4Executor is IExecutor, V4Router {
poolKey: key,
zeroForOne: zeroForOne,
amountIn: uint128(amountIn),
amountOutMinimum: uint128(amountOutMin),
amountOutMinimum: uint128(0),
hookData: bytes("")
})
);
params[1] = abi.encode(key.currency0, amountIn);
params[2] = abi.encode(key.currency1, amountOutMin);
params[2] = abi.encode(key.currency1, uint256(0));
swapData = abi.encode(actions, params);
} else {
PathKey[] memory path = new PathKey[](pools.length);
@@ -101,11 +100,11 @@ contract UniswapV4Executor is IExecutor, V4Router {
currencyIn: currencyIn,
path: path,
amountIn: uint128(amountIn),
amountOutMinimum: uint128(amountOutMin)
amountOutMinimum: uint128(0)
})
);
params[1] = abi.encode(currencyIn, amountIn);
params[2] = abi.encode(Currency.wrap(tokenOut), amountOutMin);
params[2] = abi.encode(Currency.wrap(tokenOut), uint256(0));
swapData = abi.encode(actions, params);
}
bytes memory fullData =
@@ -141,27 +140,25 @@ contract UniswapV4Executor is IExecutor, V4Router {
returns (
address tokenIn,
address tokenOut,
uint256 amountOutMin,
bool zeroForOne,
address callbackExecutor,
bytes4 callbackSelector,
UniswapV4Pool[] memory pools
)
{
if (data.length < 123) {
if (data.length < 91) {
revert UniswapV4Executor__InvalidDataLength();
}
tokenIn = address(bytes20(data[0:20]));
tokenOut = address(bytes20(data[20:40]));
amountOutMin = uint256(bytes32(data[40:72]));
zeroForOne = (data[72] != 0);
callbackExecutor = address(bytes20(data[73:93]));
callbackSelector = bytes4(data[93:97]);
zeroForOne = (data[40] != 0);
callbackExecutor = address(bytes20(data[41:61]));
callbackSelector = bytes4(data[61:65]);
uint256 poolsLength = (data.length - 97) / 26; // 26 bytes per pool object
uint256 poolsLength = (data.length - 65) / 26; // 26 bytes per pool object
pools = new UniswapV4Pool[](poolsLength);
bytes memory poolsData = data[97:];
bytes memory poolsData = data[65:];
uint256 offset = 0;
for (uint256 i = 0; i < poolsLength; i++) {
address intermediaryToken;

View File

@@ -30,6 +30,7 @@ contract Constants is Test {
address INCH_ADDR = address(0x111111111117dC0aa78b770fA6A738034120C302);
address USDE_ADDR = address(0x4c9EDD5852cd905f086C759E8383e09bff1E68B3);
address USDT_ADDR = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address PEPE_ADDR = address(0x6982508145454Ce325dDbE47a25d4ec3d2311933);
// uniswap v2
address WETH_DAI_POOL = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11;

View File

@@ -733,6 +733,37 @@ contract TychoRouterTest is TychoRouterTestSetup {
// assertGt(balancerAfter - balancerBefore, 26173932);
}
function testUSV4Integration() public {
// Test created with calldata from our router encoder, replacing the executor
// address with the USV4 executor address.
// Performs a sequential swap from USDC to PEPE though ETH using two
// consecutive USV4 pools
//
// USDC ──(USV4)──> ETH ───(USV4)──> PEPE
//
deal(USDC_ADDR, ALICE, 1 ether);
uint256 balancerBefore = IERC20(PEPE_ADDR).balanceOf(ALICE);
// Approve permit2
vm.startPrank(ALICE);
IERC20(USDC_ADDR).approve(address(permit2Address), type(uint256).max);
// Encoded solution generated using `test_split_encoding_strategy_usv4`
// but manually replacing the executor address
// `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test
// `f62849f9a0b5bf2913b396098f7c7019b51a820a`
(bool success,) = tychoRouterAddr.call(
hex"d499aa88000000000000000000000000000000000000000000000000000000003b9aca00000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000006982508145454ce325ddbe47a25d4ec3d23119330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48000000000000000000000000000000000000000000000000000000003b9aca000000000000000000000000000000000000000000000000000000000067ddee9e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067b668a6000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041bdf91011918dcb5f59ab3588212a035c770a2839fe2c19060491370fa89685b8469def9e83c7b9cf8f0ef5088a3179556a6ba1096cefbe83c09a1182981c93e41c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009400920001000000f62849f9a0b5bf2913b396098f7c7019b51a820abd0625aba0b86991c6218b36c1d19d4a2e9eb0ce3606eb486982508145454ce325ddbe47a25d4ec3d231193300f62849f9a0b5bf2913b396098f7c7019b51a820a91dd73460000000000000000000000000000000000000000000bb800003c6982508145454ce325ddbe47a25d4ec3d23119330061a80001f4000000000000000000000000"
);
vm.stopPrank();
uint256 balancerAfter = IERC20(PEPE_ADDR).balanceOf(ALICE);
assertTrue(success, "Call Failed");
assertEq(balancerAfter - balancerBefore, 97191013220606467325121599);
}
function testSingleSwapWithWrapIntegration() public {
// Test created with calldata from our router encoder, replacing the executor
// address with the USV2 executor address.
@@ -893,7 +924,6 @@ contract TychoRouterTest is TychoRouterTestSetup {
bytes memory protocolData = UniswapV4Utils.encodeExactInput(
USDE_ADDR,
USDT_ADDR,
uint256(1),
true,
address(usv4Executor),
SafeCallback.unlockCallback.selector,
@@ -939,7 +969,6 @@ contract TychoRouterTest is TychoRouterTestSetup {
bytes memory protocolData = UniswapV4Utils.encodeExactInput(
USDE_ADDR,
WBTC_ADDR,
uint256(1),
true,
address(usv4Executor),
SafeCallback.unlockCallback.selector,

View File

@@ -17,7 +17,6 @@ contract UniswapV4ExecutorExposed is UniswapV4Executor {
returns (
address tokenIn,
address tokenOut,
uint256 amountOutMin,
bool zeroForOne,
address callbackExecutor,
bytes4 callbackSelector,
@@ -44,7 +43,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
}
function testDecodeParams() public view {
uint256 minAmountOut = 100;
bool zeroForOne = true;
uint24 pool1Fee = 500;
int24 tickSpacing1 = 60;
@@ -67,7 +65,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
bytes memory data = UniswapV4Utils.encodeExactInput(
USDE_ADDR,
USDT_ADDR,
minAmountOut,
zeroForOne,
address(uniswapV4Exposed),
SafeCallback.unlockCallback.selector,
@@ -77,7 +74,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
(
address tokenIn,
address tokenOut,
uint256 amountOutMin,
bool zeroForOneDecoded,
address callbackExecutor,
bytes4 callbackSelector,
@@ -86,7 +82,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
assertEq(tokenIn, USDE_ADDR);
assertEq(tokenOut, USDT_ADDR);
assertEq(amountOutMin, minAmountOut);
assertEq(zeroForOneDecoded, zeroForOne);
assertEq(callbackExecutor, address(uniswapV4Exposed));
assertEq(callbackSelector, SafeCallback.unlockCallback.selector);
@@ -117,7 +112,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
bytes memory data = UniswapV4Utils.encodeExactInput(
USDE_ADDR,
USDT_ADDR,
uint256(1),
true,
address(uniswapV4Exposed),
SafeCallback.unlockCallback.selector,
@@ -137,7 +131,7 @@ contract UniswapV4ExecutorTest is Test, Constants {
// USDE -> USDT
// Generated by the Tycho swap encoder - test_encode_uniswap_v4_simple_swap
bytes memory protocolData =
hex"4c9edd5852cd905f086c759e8383e09bff1e68b3dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000000000001015615deb798bb3e4dfa0139dfa1b3d433cc23b72f91dd7346dac17f958d2ee523a2206206994597c13d831ec7000064000001";
hex"4c9edd5852cd905f086c759e8383e09bff1e68b3dac17f958d2ee523a2206206994597c13d831ec701f62849f9a0b5bf2913b396098f7c7019b51a820a91dd7346dac17f958d2ee523a2206206994597c13d831ec7000064000001";
uint256 amountIn = 100 ether;
deal(USDE_ADDR, address(uniswapV4Exposed), amountIn);
@@ -178,7 +172,6 @@ contract UniswapV4ExecutorTest is Test, Constants {
bytes memory data = UniswapV4Utils.encodeExactInput(
USDE_ADDR,
WBTC_ADDR,
uint256(1),
true,
address(uniswapV4Exposed),
SafeCallback.unlockCallback.selector,
@@ -200,7 +193,7 @@ contract UniswapV4ExecutorTest is Test, Constants {
// USDE -> USDT -> WBTC
// Generated by the Tycho swap encoder - test_encode_uniswap_v4_sequential_swap
bytes memory protocolData =
hex"4c9edd5852cd905f086c759e8383e09bff1e68b32260fac5e5542a773aa44fbcfedf7c193bc2c5990000000000000000000000000000000000000000000000000000000000000001015615deb798bb3e4dfa0139dfa1b3d433cc23b72f91dd7346dac17f958d2ee523a2206206994597c13d831ec70000640000012260fac5e5542a773aa44fbcfedf7c193bc2c599000bb800003c";
hex"4c9edd5852cd905f086c759e8383e09bff1e68b32260fac5e5542a773aa44fbcfedf7c193bc2c59901f62849f9a0b5bf2913b396098f7c7019b51a820a91dd7346dac17f958d2ee523a2206206994597c13d831ec70000640000012260fac5e5542a773aa44fbcfedf7c193bc2c599000bb800003c";
uint256 amountIn = 100 ether;
deal(USDE_ADDR, address(uniswapV4Exposed), amountIn);

View File

@@ -7,7 +7,6 @@ library UniswapV4Utils {
function encodeExactInput(
address tokenIn,
address tokenOut,
uint256 amountOutMin,
bool zeroForOne,
address callbackExecutor,
bytes4 callbackSelector,
@@ -27,7 +26,6 @@ library UniswapV4Utils {
return abi.encodePacked(
tokenIn,
tokenOut,
amountOutMin,
zeroForOne,
callbackExecutor,
bytes4(callbackSelector),

View File

@@ -2,7 +2,7 @@
"ethereum": {
"uniswap_v2": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
"uniswap_v3": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
"uniswap_v4": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
"uniswap_v4": "0xF62849F9A0B5Bf2913b396098F7c7019b51A820a",
"vm:balancer_v2": "0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"
}
}

View File

@@ -2,7 +2,6 @@ use std::{collections::HashSet, str::FromStr};
use alloy_primitives::{aliases::U24, FixedBytes, U256, U8};
use alloy_sol_types::SolValue;
use num_bigint::BigUint;
use tycho_core::{keccak256, Bytes};
use crate::encoding::{
@@ -187,16 +186,15 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
))
})?;
let encoding_context = EncodingContext {
receiver: solution.router_address.clone(),
exact_out: solution.exact_out,
router_address: solution.router_address.clone(),
group_token_in: tokens.first().unwrap().clone(),
group_token_out: tokens.last().unwrap().clone(),
amount_out_min: min_amount_out.clone(),
};
let mut grouped_protocol_data: Vec<u8> = vec![];
for swap in grouped_swap.swaps.iter() {
let encoding_context = EncodingContext {
receiver: solution.router_address.clone(),
exact_out: solution.exact_out,
router_address: solution.router_address.clone(),
group_token_in: grouped_swap.input_token.clone(),
group_token_out: grouped_swap.output_token.clone(),
};
let protocol_data =
swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
grouped_protocol_data.extend(protocol_data);
@@ -297,9 +295,8 @@ impl StrategyEncoder for ExecutorStrategyEncoder {
receiver: receiver.clone(),
exact_out: solution.exact_out,
router_address: router_address.clone(),
group_token_in: swap.token_in.clone(),
group_token_out: swap.token_out.clone(),
amount_out_min: BigUint::from(1u128),
group_token_in: grouped_swap.input_token.clone(),
group_token_out: grouped_swap.output_token.clone(),
};
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
grouped_protocol_data.extend(protocol_data);
@@ -327,11 +324,11 @@ impl StrategyEncoder for ExecutorStrategyEncoder {
#[cfg(test)]
mod tests {
use std::str::FromStr;
use std::{collections::HashMap, str::FromStr};
use alloy::hex::encode;
use alloy_primitives::hex;
use num_bigint::BigUint;
use num_bigint::{BigInt, BigUint};
use rstest::rstest;
use tycho_core::{
models::{protocol::ProtocolComponent, Chain as TychoCoreChain},
@@ -459,45 +456,64 @@ mod tests {
let swap_encoder_registry = get_swap_encoder_registry();
let encoder = ExecutorStrategyEncoder::new(swap_encoder_registry);
let weth = weth();
let dai = Bytes::from("0x6b175474e89094c44da98b954eedeac495271d0f");
let usdc = Bytes::from("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48");
let eth = eth();
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
let pepe = Bytes::from_str("0x6982508145454Ce325dDbE47a25d4ec3d2311933").unwrap();
let swap_a = Swap {
// Fee and tick spacing information for this test is obtained by querying the
// USV4 Position Manager contract: 0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e
// Using the poolKeys function with the first 25 bytes of the pool id
let pool_fee_usdc_eth = Bytes::from(BigInt::from(3000).to_signed_bytes_be());
let tick_spacing_usdc_eth = Bytes::from(BigInt::from(60).to_signed_bytes_be());
let mut static_attributes_usdc_eth: HashMap<String, Bytes> = HashMap::new();
static_attributes_usdc_eth.insert("fee".into(), pool_fee_usdc_eth);
static_attributes_usdc_eth.insert("tick_spacing".into(), tick_spacing_usdc_eth);
let pool_fee_eth_pepe = Bytes::from(BigInt::from(25000).to_signed_bytes_be());
let tick_spacing_eth_pepe = Bytes::from(BigInt::from(500).to_signed_bytes_be());
let mut static_attributes_eth_pepe: HashMap<String, Bytes> = HashMap::new();
static_attributes_eth_pepe.insert("fee".into(), pool_fee_eth_pepe);
static_attributes_eth_pepe.insert("tick_spacing".into(), tick_spacing_eth_pepe);
let swap_usdc_eth = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
id: "0xdce6394339af00981949f5f3baf27e3610c76326a700af57e4b3e3ae4977f78d"
.to_string(),
protocol_system: "uniswap_v4".to_string(),
static_attributes: static_attributes_usdc_eth,
..Default::default()
},
token_in: weth.clone(),
token_out: dai.clone(),
token_in: usdc.clone(),
token_out: eth.clone(),
split: 0f64,
};
let swap_b = Swap {
let swap_eth_pepe = Swap {
component: ProtocolComponent {
id: "0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5".to_string(),
id: "0xecd73ecbf77219f21f129c8836d5d686bbc27d264742ddad620500e3e548e2c9"
.to_string(),
protocol_system: "uniswap_v4".to_string(),
static_attributes: static_attributes_eth_pepe,
..Default::default()
},
token_in: dai.clone(),
token_out: usdc.clone(),
token_in: eth.clone(),
token_out: pepe.clone(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_token: weth,
given_amount: BigUint::from(1000000000000000000u64),
expected_amount: Some(BigUint::from(1000000000000000000u64)),
checked_token: usdc,
given_token: usdc,
given_amount: BigUint::from_str("1000_000000").unwrap(),
checked_token: pepe,
expected_amount: Some(BigUint::from_str("105_152_000000000000000000").unwrap()),
checked_amount: None,
sender: Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
// The receiver was generated with `makeAddr("bob") using forge`
receiver: Bytes::from_str("0x1d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e").unwrap(),
swaps: vec![swap_a, swap_b],
router_address: Bytes::from_str("0x3Ede3eCa2a72B3aeCC820E955B36f38437D01395").unwrap(),
slippage: None,
native_action: None,
sender: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
receiver: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
router_address: Bytes::from_str("0x3Ede3eCa2a72B3aeCC820E955B36f38437D01395").unwrap(),
swaps: vec![swap_usdc_eth, swap_eth_pepe],
..Default::default()
};
let (protocol_data, executor_address, selector) = encoder
@@ -506,27 +522,33 @@ mod tests {
let hex_protocol_data = encode(&protocol_data);
assert_eq!(
executor_address,
Bytes::from_str("0x5c2f5a71f67c01775180adc06909288b4c329308").unwrap()
Bytes::from_str("0xF62849F9A0B5Bf2913b396098F7c7019b51A820a").unwrap()
);
assert_eq!(
hex_protocol_data,
String::from(concat!(
// in token
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
// component id
"a478c2975ab1ea89e8196811f51a7b7ade33eb11",
// receiver
"1d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e",
// group in token
"a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
// group out token
"6982508145454ce325ddbe47a25d4ec3d2311933",
// zero for one
"00",
// in token
"6b175474e89094c44da98b954eedeac495271d0f",
// component id
"ae461ca67b15dc8dc81ce7615e0320da1a9ab8d5",
// receiver
"1d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e",
// zero for one
"01",
// executor address
"f62849f9a0b5bf2913b396098f7c7019b51a820a",
// callback selector
"91dd7346",
// first pool intermediary token (ETH)
"0000000000000000000000000000000000000000",
// fee
"000bb8",
// tick spacing
"00003c",
// second pool intermediary token (PEPE)
"6982508145454ce325ddbe47a25d4ec3d2311933",
// fee
"0061a8",
// tick spacing
"0001f4"
))
);
assert_eq!(selector, Some("swap(uint256,bytes)".to_string()));
@@ -847,39 +869,57 @@ mod tests {
#[test]
fn test_split_encoding_strategy_usv4() {
// Performs a split swap from WETH to USDC though WBTC using two consecutive USV4 pools
// Performs a sequential swap from USDC to PEPE though ETH using two consecutive USV4 pools
//
// WETH ──(USV4)──> WBTC ───(USV4)──> USDC
// USDC ──(USV4)──> ETH ───(USV4)──> PEPE
//
// Set up a mock private key for signing
// Set up a mock private key for signing (Alice's pk in our router tests)
let private_key =
"0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234".to_string();
let weth = weth();
let wbtc = Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap();
let eth = eth();
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
let pepe = Bytes::from_str("0x6982508145454Ce325dDbE47a25d4ec3d2311933").unwrap();
let swap_weth_wbtc = Swap {
// Fee and tick spacing information for this test is obtained by querying the
// USV4 Position Manager contract: 0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e
// Using the poolKeys function with the first 25 bytes of the pool id
let pool_fee_usdc_eth = Bytes::from(BigInt::from(3000).to_signed_bytes_be());
let tick_spacing_usdc_eth = Bytes::from(BigInt::from(60).to_signed_bytes_be());
let mut static_attributes_usdc_eth: HashMap<String, Bytes> = HashMap::new();
static_attributes_usdc_eth.insert("fee".into(), pool_fee_usdc_eth);
static_attributes_usdc_eth.insert("tick_spacing".into(), tick_spacing_usdc_eth);
let pool_fee_eth_pepe = Bytes::from(BigInt::from(25000).to_signed_bytes_be());
let tick_spacing_eth_pepe = Bytes::from(BigInt::from(500).to_signed_bytes_be());
let mut static_attributes_eth_pepe: HashMap<String, Bytes> = HashMap::new();
static_attributes_eth_pepe.insert("fee".into(), pool_fee_eth_pepe);
static_attributes_eth_pepe.insert("tick_spacing".into(), tick_spacing_eth_pepe);
let swap_usdc_eth = Swap {
component: ProtocolComponent {
id: "0xBb2b8038a1640196FbE3e38816F3e67Cba72D940".to_string(),
id: "0xdce6394339af00981949f5f3baf27e3610c76326a700af57e4b3e3ae4977f78d"
.to_string(),
protocol_system: "uniswap_v4".to_string(),
static_attributes: static_attributes_usdc_eth,
..Default::default()
},
token_in: weth.clone(),
token_out: wbtc.clone(),
// This represents the remaining 50%, but to avoid any rounding errors we set this to
// 0 to signify "the remainder of the WETH value". It should still be very close to 50%
token_in: usdc.clone(),
token_out: eth.clone(),
split: 0f64,
};
let swap_wbtc_usdc = Swap {
let swap_eth_pepe = Swap {
component: ProtocolComponent {
id: "0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5".to_string(),
id: "0xecd73ecbf77219f21f129c8836d5d686bbc27d264742ddad620500e3e548e2c9"
.to_string(),
protocol_system: "uniswap_v4".to_string(),
static_attributes: static_attributes_eth_pepe,
..Default::default()
},
token_in: wbtc.clone(),
token_out: usdc.clone(),
token_in: eth.clone(),
token_out: pepe.clone(),
split: 0f64,
};
let swap_encoder_registry = get_swap_encoder_registry();
@@ -887,16 +927,16 @@ mod tests {
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
let solution = Solution {
exact_out: false,
given_token: weth,
given_amount: BigUint::from_str("1_000000000000000000").unwrap(),
checked_token: usdc,
expected_amount: Some(BigUint::from_str("3_000_000000").unwrap()),
given_token: usdc,
given_amount: BigUint::from_str("1000_000000").unwrap(),
checked_token: pepe,
expected_amount: Some(BigUint::from_str("105_152_000000000000000000").unwrap()),
checked_amount: None,
slippage: None,
sender: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
receiver: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
router_address: Bytes::from_str("0x3Ede3eCa2a72B3aeCC820E955B36f38437D01395").unwrap(),
swaps: vec![swap_weth_wbtc, swap_wbtc_usdc],
swaps: vec![swap_usdc_eth, swap_eth_pepe],
..Default::default()
};
@@ -906,9 +946,9 @@ mod tests {
let expected_input = [
"d499aa88", // Function selector
"0000000000000000000000000000000000000000000000000de0b6b3a7640000", // amount out
"000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in
"000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // token out
"000000000000000000000000000000000000000000000000000000003b9aca00", // amount in
"000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // token in
"0000000000000000000000006982508145454ce325ddbe47a25d4ec3d2311933", // token out
"0000000000000000000000000000000000000000000000000000000000000000", // min amount out
"0000000000000000000000000000000000000000000000000000000000000000", // wrap
"0000000000000000000000000000000000000000000000000000000000000000", // unwrap
@@ -939,29 +979,34 @@ mod tests {
let expected_swaps = String::from(concat!(
// length of ple encoded swaps without padding
"0000000000000000000000000000000000000000000000000000000000000099",
"0000000000000000000000000000000000000000000000000000000000000094",
// ple encoded swaps
"0097", // Swap length
"0092", // Swap length
"00", // token in index
"01", // token out index
"000000", // split
// Swap data header
"5c2f5a71f67c01775180adc06909288b4c329308", // executor address
"f62849f9a0b5bf2913b396098f7c7019b51a820a", // executor address
"bd0625ab", // selector
// First swap protocol data
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in
"bb2b8038a1640196fbe3e38816f3e67cba72d940", // component id
"3ede3eca2a72b3aecc820e955b36f38437d01395", // receiver
// Protocol data
"a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // group token in
"6982508145454ce325ddbe47a25d4ec3d2311933", // group token in
"00", // zero2one
// Second swap protocol data
"2260fac5e5542a773aa44fbcfedf7c193bc2c599", // token in
"ae461ca67b15dc8dc81ce7615e0320da1a9ab8d5", // component id
"3ede3eca2a72b3aecc820e955b36f38437d01395", // receiver
"01", // zero2one
"00000000000000", // padding
"f62849f9a0b5bf2913b396098f7c7019b51a820a", // executor address
"91dd7346", // callback selector
// First pool params
"0000000000000000000000000000000000000000", // intermediary token (ETH)
"000bb8", // fee
"00003c", // tick spacing
// Second pool params
"6982508145454ce325ddbe47a25d4ec3d2311933", // intermediary token (PEPE)
"0061a8", // fee
"0001f4", // tick spacing
"000000000000000000000000" // padding
));
let hex_calldata = encode(&calldata);
println!("{}", hex_calldata);
assert_eq!(hex_calldata[..520], expected_input);
assert_eq!(hex_calldata[1288..], expected_swaps);
}

View File

@@ -1,7 +1,7 @@
use crate::encoding::{
errors::EncodingError,
evm::swap_encoder::swap_encoders::{
BalancerV2SwapEncoder, UniswapV2SwapEncoder, UniswapV3SwapEncoder,
BalancerV2SwapEncoder, UniswapV2SwapEncoder, UniswapV3SwapEncoder, UniswapV4SwapEncoder,
},
swap_encoder::SwapEncoder,
};
@@ -26,7 +26,7 @@ impl SwapEncoderBuilder {
"vm:balancer_v2" => Ok(Box::new(BalancerV2SwapEncoder::new(self.executor_address))),
"uniswap_v3" => Ok(Box::new(UniswapV3SwapEncoder::new(self.executor_address))),
// TODO replace this with V4 encoder once implemented
"uniswap_v4" => Ok(Box::new(UniswapV2SwapEncoder::new(self.executor_address))),
"uniswap_v4" => Ok(Box::new(UniswapV4SwapEncoder::new(self.executor_address))),
_ => Err(EncodingError::FatalError(format!(
"Unknown protocol system: {}",
self.protocol_system

View File

@@ -2,14 +2,14 @@ use std::str::FromStr;
use alloy_primitives::{Address, Bytes as AlloyBytes};
use alloy_sol_types::SolValue;
use tycho_core::Bytes;
use crate::encoding::{
errors::EncodingError,
evm::{
approvals::protocol_approvals_manager::ProtocolApprovalsManager,
utils::{
biguint_to_u256, bytes_to_address, encode_function_selector, get_static_attribute,
pad_to_fixed_size,
bytes_to_address, encode_function_selector, get_static_attribute, pad_to_fixed_size,
},
},
models::{EncodingContext, Swap},
@@ -174,7 +174,7 @@ impl SwapEncoder for UniswapV4SwapEncoder {
let pool_fee_u24 = pad_to_fixed_size::<3>(&fee)
.map_err(|_| EncodingError::FatalError("Failed to pad fee bytes".to_string()))?;
let tick_spacing = get_static_attribute(&swap, "tickSpacing")?;
let tick_spacing = get_static_attribute(&swap, "tick_spacing")?;
let pool_tick_spacing_u24 = pad_to_fixed_size::<3>(&tick_spacing).map_err(|_| {
EncodingError::FatalError("Failed to pad tick spacing bytes".to_string())
@@ -192,9 +192,11 @@ impl SwapEncoder for UniswapV4SwapEncoder {
let group_token_in_address = bytes_to_address(&encoding_context.group_token_in)?;
let group_token_out_address = bytes_to_address(&encoding_context.group_token_out)?;
let amount_out_min = biguint_to_u256(&encoding_context.amount_out_min);
let zero_to_one = Self::get_zero_to_one(token_in_address, token_out_address);
let callback_executor = bytes_to_address(&encoding_context.router_address)?;
let callback_executor =
bytes_to_address(&Bytes::from_str(&self.executor_address).map_err(|_| {
EncodingError::FatalError("Invalid UniswapV4 executor address".into())
})?)?;
let pool_params =
(token_out_address, pool_fee_u24, pool_tick_spacing_u24).abi_encode_packed();
@@ -202,7 +204,6 @@ impl SwapEncoder for UniswapV4SwapEncoder {
let args = (
group_token_in_address,
group_token_out_address,
amount_out_min,
zero_to_one,
callback_executor,
encode_function_selector(&self.callback_selector),
@@ -289,7 +290,7 @@ mod tests {
use std::collections::HashMap;
use alloy::hex::encode;
use num_bigint::{BigInt, BigUint};
use num_bigint::BigInt;
use tycho_core::{models::protocol::ProtocolComponent, Bytes};
use super::*;
@@ -315,7 +316,6 @@ mod tests {
router_address: Bytes::zero(20),
group_token_in: token_in.clone(),
group_token_out: token_out.clone(),
amount_out_min: BigUint::from(0u128),
};
let encoder =
UniswapV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
@@ -363,7 +363,6 @@ mod tests {
router_address: Bytes::zero(20),
group_token_in: token_in.clone(),
group_token_out: token_out.clone(),
amount_out_min: BigUint::from(0u128),
};
let encoder =
UniswapV3SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
@@ -412,7 +411,6 @@ mod tests {
router_address: Bytes::zero(20),
group_token_in: token_in.clone(),
group_token_out: token_out.clone(),
amount_out_min: BigUint::from(0u128),
};
let encoder =
BalancerV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
@@ -443,14 +441,13 @@ mod tests {
fn test_encode_uniswap_v4_simple_swap() {
let fee = BigInt::from(100);
let tick_spacing = BigInt::from(1);
let encoded_pool_fee = Bytes::from(fee.to_signed_bytes_be());
let encoded_tick_spacing = Bytes::from(tick_spacing.to_signed_bytes_be());
let token_in = Bytes::from("0x4c9EDD5852cd905f086C759E8383e09bff1E68B3"); // USDE
let token_out = Bytes::from("0xdAC17F958D2ee523a2206206994597C13D831ec7"); // USDT
let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
static_attributes.insert("fee".into(), Bytes::from(encoded_pool_fee.to_vec()));
static_attributes.insert("tickSpacing".into(), Bytes::from(encoded_tick_spacing.to_vec()));
static_attributes.insert("fee".into(), Bytes::from(fee.to_signed_bytes_be()));
static_attributes
.insert("tick_spacing".into(), Bytes::from(tick_spacing.to_signed_bytes_be()));
let usv4_pool = ProtocolComponent {
// Pool manager
@@ -474,10 +471,9 @@ mod tests {
group_token_in: token_in.clone(),
group_token_out: token_out.clone(),
amount_out_min: BigUint::from(1u128),
};
let encoder =
UniswapV4SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
UniswapV4SwapEncoder::new(String::from("0xF62849F9A0B5Bf2913b396098F7c7019b51A820a"));
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.unwrap();
@@ -490,12 +486,10 @@ mod tests {
"4c9edd5852cd905f086c759e8383e09bff1e68b3",
// group token out
"dac17f958d2ee523a2206206994597c13d831ec7",
// amount out min (0 as u128)
"0000000000000000000000000000000000000000000000000000000000000001",
// zero for one
"01",
// router address
"5615deb798bb3e4dfa0139dfa1b3d433cc23b72f",
// executor address
"f62849f9a0b5bf2913b396098f7c7019b51a820a",
// callback selector for "unlockCallback(bytes)"
"91dd7346",
// pool params:
@@ -513,15 +507,14 @@ mod tests {
fn test_encode_uniswap_v4_second_swap() {
let fee = BigInt::from(3000);
let tick_spacing = BigInt::from(60);
let encoded_pool_fee = Bytes::from(fee.to_signed_bytes_be());
let encoded_tick_spacing = Bytes::from(tick_spacing.to_signed_bytes_be());
let group_token_in = Bytes::from("0x4c9EDD5852cd905f086C759E8383e09bff1E68B3"); // USDE
let token_in = Bytes::from("0xdAC17F958D2ee523a2206206994597C13D831ec7"); // USDT
let token_out = Bytes::from("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"); // WBTC
let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
static_attributes.insert("fee".into(), Bytes::from(encoded_pool_fee.to_vec()));
static_attributes.insert("tickSpacing".into(), Bytes::from(encoded_tick_spacing.to_vec()));
static_attributes.insert("fee".into(), Bytes::from(fee.to_signed_bytes_be()));
static_attributes
.insert("tick_spacing".into(), Bytes::from(tick_spacing.to_signed_bytes_be()));
let usv4_pool = ProtocolComponent {
id: String::from("0x000000000004444c5dc75cB358380D2e3dE08A90"),
@@ -543,7 +536,6 @@ mod tests {
group_token_in: group_token_in.clone(),
// Token out is the same as the group token out
group_token_out: token_out.clone(),
amount_out_min: BigUint::from(1u128),
};
let encoder =
@@ -582,21 +574,19 @@ mod tests {
router_address: router_address.clone(),
group_token_in: usde_address.clone(),
group_token_out: wbtc_address.clone(),
amount_out_min: BigUint::from(1u128),
};
// Setup - First sequence: USDE -> USDT
let usde_usdt_fee = BigInt::from(100);
let usde_usdt_tick_spacing = BigInt::from(1);
let usde_usdt_encoded_pool_fee = Bytes::from(usde_usdt_fee.to_signed_bytes_be());
let usde_usdt_encoded_tick_spacing =
Bytes::from(usde_usdt_tick_spacing.to_signed_bytes_be());
let mut usde_usdt_static_attributes: HashMap<String, Bytes> = HashMap::new();
usde_usdt_static_attributes
.insert("fee".into(), Bytes::from(usde_usdt_encoded_pool_fee.to_vec()));
usde_usdt_static_attributes
.insert("tickSpacing".into(), Bytes::from(usde_usdt_encoded_tick_spacing.to_vec()));
.insert("fee".into(), Bytes::from(usde_usdt_fee.to_signed_bytes_be()));
usde_usdt_static_attributes.insert(
"tick_spacing".into(),
Bytes::from(usde_usdt_tick_spacing.to_signed_bytes_be()),
);
let usde_usdt_component = ProtocolComponent {
id: String::from("0x000000000004444c5dc75cB358380D2e3dE08A90"),
@@ -607,15 +597,14 @@ mod tests {
// Setup - Second sequence: USDT -> WBTC
let usdt_wbtc_fee = BigInt::from(3000);
let usdt_wbtc_tick_spacing = BigInt::from(60);
let usdt_wbtc_encoded_pool_fee = Bytes::from(usdt_wbtc_fee.to_signed_bytes_be());
let usdt_wbtc_encoded_tick_spacing =
Bytes::from(usdt_wbtc_tick_spacing.to_signed_bytes_be());
let mut usdt_wbtc_static_attributes: HashMap<String, Bytes> = HashMap::new();
usdt_wbtc_static_attributes
.insert("fee".into(), Bytes::from(usdt_wbtc_encoded_pool_fee.to_vec()));
usdt_wbtc_static_attributes
.insert("tickSpacing".into(), Bytes::from(usdt_wbtc_encoded_tick_spacing.to_vec()));
.insert("fee".into(), Bytes::from(usdt_wbtc_fee.to_signed_bytes_be()));
usdt_wbtc_static_attributes.insert(
"tick_spacing".into(),
Bytes::from(usdt_wbtc_tick_spacing.to_signed_bytes_be()),
);
let usdt_wbtc_component = ProtocolComponent {
id: String::from("0x000000000004444c5dc75cB358380D2e3dE08A90"),
@@ -638,7 +627,7 @@ mod tests {
};
let encoder =
UniswapV4SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
UniswapV4SwapEncoder::new(String::from("0xF62849F9A0B5Bf2913b396098F7c7019b51A820a"));
let initial_encoded_swap = encoder
.encode_swap(initial_swap, context.clone())
.unwrap();
@@ -656,12 +645,10 @@ mod tests {
"4c9edd5852cd905f086c759e8383e09bff1e68b3",
// group_token out
"2260fac5e5542a773aa44fbcfedf7c193bc2c599",
// amount out min (1 as u128)
"0000000000000000000000000000000000000000000000000000000000000001",
// zero for one
"01",
// router address
"5615deb798bb3e4dfa0139dfa1b3d433cc23b72f",
// executor address
"f62849f9a0b5bf2913b396098f7c7019b51a820a",
// callback selector for "unlockCallback(bytes)"
"91dd7346",
// pool params:

View File

@@ -108,7 +108,6 @@ pub struct Transaction {
/// * `router_address`: Address of the router contract to be used for the swaps.
/// * `group_token_in`: Token to be used as the input for the group swap.
/// * `group_token_out`: Token to be used as the output for the group swap.
/// * `amount_out_min`: Minimum amount of the output token to be received.
#[derive(Clone, Debug)]
pub struct EncodingContext {
pub receiver: Bytes,
@@ -116,7 +115,6 @@ pub struct EncodingContext {
pub router_address: Bytes,
pub group_token_in: Bytes,
pub group_token_out: Bytes,
pub amount_out_min: BigUint,
}
#[derive(Clone, PartialEq, Eq, Hash)]