Skip to content

Commit

Permalink
Pending changes exported from your codespace
Browse files Browse the repository at this point in the history
  • Loading branch information
ts0yu committed Aug 9, 2024
1 parent 6f41aad commit 66c4f45
Show file tree
Hide file tree
Showing 9 changed files with 321 additions and 166 deletions.
258 changes: 176 additions & 82 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ version = "0.1.0"
edition = "2021"

[dependencies]
alloy = { version = "0.1.3", features = ["rlp", "node-bindings", "sol-types", "contract", "transports", "transport-http", "rpc"] }
alloy = { version = "0.2.1", features = ["rlp", "node-bindings", "sol-types", "contract", "transports", "transport-http", "rpc", "providers"] }
tokio = { version = "1.36.0", features = ["full"] }
revm = "10.0.0"
octane = { git = "https://github.com/arena-rs/octane" }
Expand All @@ -24,6 +24,7 @@ futures = "0.3.30"
rand = "0.8.5"
rand_distr = "0.4.3"
bytes = "1.6.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[lib]
doctest = false
Expand Down
10 changes: 5 additions & 5 deletions contracts/utils/src/LiquidityProvider.sol
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ contract LiquidityProvider is PoolTestBase {
}

function unlockCallback(bytes calldata rawData) external returns (bytes memory) {
require(msg.sender == address(manager));
require(msg.sender == address(manager), "error 0");

CallbackData memory data = abi.decode(rawData, (CallbackData));

Expand All @@ -81,11 +81,11 @@ contract LiquidityProvider is PoolTestBase {
);

if (data.params.liquidityDelta < 0) {
assert(delta0 > 0 || delta1 > 0);
assert(!(delta0 < 0 || delta1 < 0));
require(delta0 > 0 || delta1 > 0, "error 1");
require(!(delta0 < 0 || delta1 < 0), "error 2");
} else if (data.params.liquidityDelta > 0) {
assert(delta0 < 0 || delta1 < 0);
assert(!(delta0 > 0 || delta1 > 0));
require(delta0 < 0 || delta1 < 0, "error 3");
require(!(delta0 > 0 || delta1 > 0), "error 4");
}

if (delta0 < 0) data.key.currency0.settle(manager, data.sender, uint256(-delta0), data.settleUsingBurn);
Expand Down
63 changes: 63 additions & 0 deletions contracts/utils/test/LiquidityProvider.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolManager} from "v4-core/PoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {LiquidityProvider} from "../src/LiquidityProvider.sol";
import {ArenaToken} from "../src/ArenaToken.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {CurrencyLibrary, Currency} from "v4-core/types/Currency.sol";
import "forge-std/Test.sol";

contract LiquidityProviderTest is Test {
PoolManager public manager;
LiquidityProvider public lpRouter;
ArenaToken public token0;
ArenaToken public token1;

function test_createLiquidity() external {
vm.startPrank(address(0x1)); // Set caller one's address

manager = new PoolManager(5000);
lpRouter = new LiquidityProvider(manager);

token0 = new ArenaToken("Token0", "T0", 18);
token1 = new ArenaToken("Token1", "T1", 18);

if (address(token0) > address(token1)) {
(token0, token1) = (token1, token0);
}

PoolKey memory pool = PoolKey({
currency0: Currency.wrap(address(token0)),
currency1: Currency.wrap(address(token1)),
fee: 3000,
tickSpacing: 60,
hooks: IHooks(address(0x0))
});

manager.initialize(pool, 79228162514264337593543950336, "");

vm.stopPrank();
vm.startPrank(address(0x2));

token0.mint(2 ** 255);
token1.mint(2 ** 255);

token0.approve(address(lpRouter), type(uint256).max);
token1.approve(address(lpRouter), type(uint256).max);

IPoolManager.ModifyLiquidityParams memory params = IPoolManager.ModifyLiquidityParams({
tickLower: -120,
tickUpper: 120,
liquidityDelta: 1e18,
salt: ""
});

lpRouter.modifyLiquidity(pool, params, "");

vm.stopPrank();
}
}
3 changes: 3 additions & 0 deletions src/bindings/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ pub mod Fetcher {
}
#[automatically_derived]
impl alloy_sol_types::SolType for Currency {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = alloy::sol_types::private::Address;
type Token<'a> =
<alloy::sol_types::sol_data::Address as alloy_sol_types::SolType>::Token<'a>;
Expand Down Expand Up @@ -357,6 +358,7 @@ pub mod Fetcher {
}
#[automatically_derived]
impl alloy_sol_types::SolType for PoolId {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = alloy::sol_types::private::FixedBytes<32>;
type Token<'a> =
<alloy::sol_types::sol_data::FixedBytes<32> as alloy_sol_types::SolType>::Token<'a>;
Expand Down Expand Up @@ -516,6 +518,7 @@ pub mod Fetcher {
}
#[automatically_derived]
impl alloy_sol_types::SolType for PoolKey {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = Self;
type Token<'a> = <UnderlyingSolTuple<'a> as alloy_sol_types::SolType>::Token<'a>;
const SOL_NAME: &'static str = <Self as alloy_sol_types::SolStruct>::NAME;
Expand Down
16 changes: 10 additions & 6 deletions src/bindings/liquidityprovider.rs

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions src/bindings/poolmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1460,6 +1460,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for BalanceDelta {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = alloy::sol_types::private::I256;
type Token<'a> =
<alloy::sol_types::sol_data::Int<256> as alloy_sol_types::SolType>::Token<'a>;
Expand Down Expand Up @@ -1565,6 +1566,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for Currency {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = alloy::sol_types::private::Address;
type Token<'a> =
<alloy::sol_types::sol_data::Address as alloy_sol_types::SolType>::Token<'a>;
Expand Down Expand Up @@ -1669,6 +1671,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for PoolId {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = alloy::sol_types::private::FixedBytes<32>;
type Token<'a> =
<alloy::sol_types::sol_data::FixedBytes<32> as alloy_sol_types::SolType>::Token<'a>;
Expand Down Expand Up @@ -1823,6 +1826,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for ModifyLiquidityParams {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = Self;
type Token<'a> = <UnderlyingSolTuple<'a> as alloy_sol_types::SolType>::Token<'a>;
const SOL_NAME: &'static str = <Self as alloy_sol_types::SolStruct>::NAME;
Expand Down Expand Up @@ -2054,6 +2058,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for PoolKey {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = Self;
type Token<'a> = <UnderlyingSolTuple<'a> as alloy_sol_types::SolType>::Token<'a>;
const SOL_NAME: &'static str = <Self as alloy_sol_types::SolStruct>::NAME;
Expand Down Expand Up @@ -2271,6 +2276,7 @@ pub mod PoolManager {
}
#[automatically_derived]
impl alloy_sol_types::SolType for SwapParams {
const PACKED_ENCODED_SIZE: std::option::Option<usize> = None;
type RustType = Self;
type Token<'a> = <UnderlyingSolTuple<'a> as alloy_sol_types::SolType>::Token<'a>;
const SOL_NAME: &'static str = <Self as alloy_sol_types::SolStruct>::NAME;
Expand Down
118 changes: 51 additions & 67 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use octane::{
AnvilProvider,
};
use serde::{Deserialize, Serialize};

use alloy::providers::Provider;
use crate::{
arbitrageur::Arbitrageur,
bindings::{
Expand Down Expand Up @@ -65,89 +65,73 @@ mod tests {
client: Arc<AnvilProvider>,
messager: Messager,
) -> Result<Option<EventStream<Message>>> {
let mut tokens = Vec::new();
let mut stream = messager.clone().stream().unwrap();

messager.send(To::All, DeploymentRequest::Token {
name: "Arena Token 0".to_string(),
symbol: "ARENA0".to_string(),
decimals: 18,
}).await?;

messager.send(To::All, DeploymentRequest::Token {
name: "Arena Token 1".to_string(),
symbol: "ARENA1".to_string(),
decimals: 18,
}).await?;

while let Some(event) = stream.next().await {
let query: DeploymentResponse = match serde_json::from_str(&event.data) {
Ok(query) => query,
Err(_) => continue,
};

if let DeploymentResponse::Token(address) = query {
tokens.push(address);
}

if tokens.len() == 2 {
break;
}
}

if tokens[0] > tokens[1] {
tokens.swap(0, 1);
}

let pool_manager = PoolManager::deploy(client.clone(), Uint::from(5000)).await.unwrap();

// Deploy tokens
let currency0 = ArenaToken::deploy(client.clone(), "ARENA0".to_string(), "ARENA0".to_string(), 18).await?;
let currency1 = ArenaToken::deploy(client.clone(), "ARENA1".to_string(), "ARENA1".to_string(), 18).await?;

// Mint tokens
currency0.mint(Uint::from(2).pow(Uint::from(255))).send().await?.watch().await?;
currency1.mint(Uint::from(2).pow(Uint::from(255))).send().await?.watch().await?;

// Ensure the token addresses are ordered
let (currency0, currency1) = if currency0.address() > currency1.address() {
(currency1, currency0)
} else {
(currency0, currency1)
};

// Create PoolKey
let key = PoolKey {
currency0: tokens[0],
currency1: tokens[1],
fee: 3000,
currency0: *currency0.address(),
currency1: *currency1.address(),
fee: 2000,
tickSpacing: 60,
hooks: Address::default()
hooks: Address::default(),
};

messager.send(To::All, DeploymentRequest::Pool(PoolParams {
key: key.clone(),
sqrt_price_x96: U256::from(79228162514264337593543950336_u128),
hook_data: Bytes::default(),
})).await?;

let lp_key = LPoolKey {
currency0: key.currency0,
currency1: key.currency1,
fee: key.fee,
tickSpacing: key.tickSpacing,
hooks: key.hooks,
};

// Initialize pool
pool_manager.initialize(key.clone(), U256::from(79228162514264337593543950336_u128), Bytes::default()).send().await?.watch().await?;

// Deploy LiquidityProvider
let liquidity_provider = LiquidityProvider::deploy(client.clone(), *pool_manager.address()).await.unwrap();

// Approve tokens for LiquidityProvider
currency0.approve(*liquidity_provider.address(), Uint::MAX).send().await?.watch().await?;
currency1.approve(*liquidity_provider.address(), Uint::MAX).send().await?.watch().await?;

// Create ModifyLiquidityParams
let modification = ModifyLiquidityParams {
tickLower: -120,
tickUpper: 120,
liquidityDelta: I256::from_str("1000000000000000000").unwrap(),
salt: <FixedBytes<32> as SolType>::abi_decode(&[0u8; 32], true)
.unwrap(),
liquidityDelta: I256::from_str("100000000000000000").unwrap(),
salt: <FixedBytes<32> as SolType>::abi_decode(&[0u8; 32], true).unwrap(),
};

println!("{:#?}", modification);

messager.send(To::All, AllocationRequest {
pool: key,
modification,
hook_data: Bytes::default(),
}).await?;

Ok(Some(stream))

// Modify liquidity
let tx = liquidity_provider.modifyLiquidity_1(lp_key, modification, Bytes::default());
let send_result = tx.send().await;

println!("send result: {:#?}", send_result);
Ok(Some(messager.stream().unwrap()))
}
}

#[tokio::test]
async fn test_lp() {
env_logger::init();

let harness = Agent::builder("harness").with_behavior(Harness::default());
let deployer = Agent::builder("deployer")
.with_behavior(Deployer::default());

let liq_admin = Agent::builder("admin")
.with_behavior(LiquidityAdmin::default());

let mut world = World::new("id");

world.add_agent(deployer);
world.add_agent(liq_admin);
world.add_agent(harness);

let _ = world.run().await;
Expand Down
10 changes: 5 additions & 5 deletions src/liquidity_admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,13 @@ impl Behavior<Message> for LiquidityAdmin {
}

async fn process(&mut self, event: Message) -> Result<ControlFlow> {
let query: AllocationRequest = match serde_json::from_str(&event.data) {
let mut query: AllocationRequest = match serde_json::from_str(&event.data) {
Ok(query) => query,
Err(_) => return Ok(ControlFlow::Continue),
};



let liquidity_provider = LiquidityProvider::deploy(self.base.client.clone().unwrap(), self.deployment.unwrap())
.await
.unwrap();
Expand Down Expand Up @@ -79,14 +81,11 @@ impl Behavior<Message> for LiquidityAdmin {
let lp_key = LPoolKey {
currency0: key.currency0,
currency1: key.currency1,
fee: key.fee,
fee: key.fee + 1,
tickSpacing: key.tickSpacing,
hooks: key.hooks,
};

println!("lp_key: {:#?}", lp_key);
println!("query.modification.tickLower: {:#?}", query.modification.tickLower);

let tx = liquidity_provider.modifyLiquidity_1(
lp_key,
query.modification,
Expand All @@ -101,6 +100,7 @@ impl Behavior<Message> for LiquidityAdmin {

// println!("watch result: {:#?}", watch_result);


Ok(ControlFlow::Continue)
}
}

0 comments on commit 66c4f45

Please sign in to comment.