Skip to content
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

Feat/mainnet arb scripts #27

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
491 changes: 491 additions & 0 deletions broadcast/ComputeArb.s.sol/753712/run-1718911400.json

Large diffs are not rendered by default.

491 changes: 491 additions & 0 deletions broadcast/ComputeArb.s.sol/753712/run-1718911779.json

Large diffs are not rendered by default.

491 changes: 491 additions & 0 deletions broadcast/ComputeArb.s.sol/753712/run-latest.json

Large diffs are not rendered by default.

84 changes: 84 additions & 0 deletions broadcast/DeployFactory.s.sol/753712/run-1718989078.json

Large diffs are not rendered by default.

48 changes: 24 additions & 24 deletions broadcast/DeployFactory.s.sol/753712/run-latest.json

Large diffs are not rendered by default.

1,112 changes: 1,112 additions & 0 deletions broadcast/DeployPool.s.sol/753712/run-1718988813.json

Large diffs are not rendered by default.

1,034 changes: 1,034 additions & 0 deletions broadcast/DeployPool.s.sol/753712/run-1718989196.json

Large diffs are not rendered by default.

1,112 changes: 1,112 additions & 0 deletions broadcast/DeployPool.s.sol/753712/run-1718989251.json

Large diffs are not rendered by default.

636 changes: 318 additions & 318 deletions broadcast/DeployPool.s.sol/753712/run-latest.json

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions script/ArbMath.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

import "solmate/utils/FixedPointMathLib.sol";
import "solstat/Gaussian.sol";
import "solstat/Invariant.sol";

contract ArbMath {
using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;

constructor() { }

function cdf(int256 input) public pure returns (int256 output) {
output = Gaussian.cdf(input);
}

function pdf(int256 input) public pure returns (int256 output) {
output = Gaussian.pdf(input);
}

function ppf(int256 input) public pure returns (int256 output) {
output = Gaussian.ppf(input);
}

function mulWadDown(uint256 x, uint256 y) public pure returns (uint256 z) {
z = FixedPointMathLib.mulWadDown(x, y);
}

function mulWadUp(uint256 x, uint256 y) public pure returns (uint256 z) {
z = FixedPointMathLib.mulWadUp(x, y);
}

function divWadDown(uint256 x, uint256 y) public pure returns (uint256 z) {
z = FixedPointMathLib.divWadDown(x, y);
}

function divWadUp(uint256 x, uint256 y) public pure returns (uint256 z) {
z = FixedPointMathLib.divWadUp(x, y);
}

function log(int256 x) public pure returns (int256 z) {
z = FixedPointMathLib.lnWad(x);
}

function sqrt(uint256 x) public pure returns (uint256 z) {
z = FixedPointMathLib.sqrt(x);
}

function pow(int256 x, int256 y) public pure returns (int256 z) {
z = FixedPointMathLib.powWad(x, y);
}
}
78 changes: 78 additions & 0 deletions script/BisectionLib.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.13;
import "forge-std/console2.sol";

/// @dev Thrown when the lower bound is greater than the upper bound.
error BisectionLib_InvalidBounds(uint256 lower, uint256 upper);
/// @dev Thrown when the result of the function `fx` for each input, `upper` and `lower`, is the same sign.
error BisectionLib_RootOutsideBounds(int256 lowerResult, int256 upperResult);

/**
* @notice
* The function `fx` must be continuous and monotonic.
*
* @dev
* Bisection is a method of finding the root of a function.
* The root is the point where the function crosses the x-axis.
*
* @param args The arguments to pass to the function `fx`.
* @param lower The lower bound of the root to find.
* @param upper The upper bound of the root to find.
* @param epsilon The maximum distance between the lower and upper results.
* @param maxIterations The maximum amount of loop iterations to run.
* @param fx The function to find the root of.
* @return root The root of the function `fx`.
*/
function bisection(
bytes memory args,
uint256 lower,
uint256 upper,
uint256 epsilon,
uint256 maxIterations,
function (bytes memory,uint256) pure returns (int256) fx
) pure returns (uint256 root, uint256 upperInput, uint256 lowerInput) {
if (lower > upper) revert BisectionLib_InvalidBounds(lower, upper);
// Passes the lower and upper bounds to the optimized function.
// Reverts if the optimized function `fx` returns both negative or both positive values.
// This means that the root is not between the bounds.
// The root is between the bounds if the product of the two values is negative.
int256 lowerOutput = fx(args, lower);
int256 upperOutput = fx(args, upper);
console2.log("lowerOutput: ", lowerOutput);
console2.log("lower: ", lower);
console2.log("upperOutput: ", upperOutput);
console2.log("upper: ", upper);
if (lowerOutput * upperOutput > 0) {
revert BisectionLib_RootOutsideBounds(lowerOutput, upperOutput);
}

// Distance is optimized to equal `epsilon`.
uint256 distance = upper - lower;
upperInput = upper;
lowerInput = lower;

uint256 iterations; // Bounds the amount of loops to `maxIterations`.
do {
// Bisection uses the point between the lower and upper bounds.
// The `distance` is halved each iteration.
root = (lowerInput + upperInput) / 2;

int256 output = fx(args, root);

// If the product is negative, the root is between the lower and root.
// If the product is positive, the root is between the root and upper.
if (output * lowerOutput <= 0) {
upperInput = root; // Set the new upper bound to the root because we know its between the lower and root.
} else {
lowerInput = root; // Set the new lower bound to the root because we know its between the upper and root.
lowerOutput = output; // root function value becomes new lower output value
}

// Update the distance with the new bounds.
distance = upper - lower;

unchecked {
iterations++; // Increment the iterator.
}
} while (distance > epsilon && iterations < maxIterations);
}
140 changes: 140 additions & 0 deletions script/ComputeArb.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Script, console2} from "forge-std/Script.sol";
import {ERC20, RMM, PoolPreCompute} from "../src/RMM.sol";
import {LiquidityManager} from "../src/LiquidityManager.sol";
import {Factory} from "../src/Factory.sol";

import {computeSpotPrice} from "../src/lib/RmmLib.sol";

import {IPMarket} from "pendle/interfaces/IPMarket.sol";
import {IStandardizedYield} from "pendle/interfaces/IStandardizedYield.sol";
import {IPYieldToken} from "pendle/interfaces/IPYieldToken.sol";
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";
import {RmmArbitrage, RmmParams} from "./RmmArbitrage.sol";
import {ArbMath} from "./ArbMath.sol";
import {Gaussian} from "../lib/solstat/src/Gaussian.sol";
import { SignedWadMathLib } from "./SignedWadMathLib.sol";

import "pendle/core/Market/MarketMathCore.sol";
import "pendle/interfaces/IPAllActionV3.sol";

contract ComputeArb is Script, RmmArbitrage, ArbMath {
using MarketMathCore for MarketState;
using MarketMathCore for int256;
using MarketMathCore for uint256;
using FixedPointMathLib for uint256;
using PYIndexLib for IPYieldToken;
using PYIndexLib for PYIndex;
using SignedWadMathLib for int256;

uint256 mainnetFork;
uint256 testnetFork;

IPMarket market = IPMarket(0xC374f7eC85F8C7DE3207a10bB1978bA104bdA3B2);
IPAllActionV3 router = IPAllActionV3(0x00000000005BBB0EF59571E58418F9a4357b68A0);
address wstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0; //real wsteth

IStandardizedYield public SY;
IPPrincipalToken public PT;
IPYieldToken public YT;
MarketState public mktState;

int256 rateAnchor;
int256 rateScalar;
uint256 timeToExpiry;

RMM rmm = RMM(payable(0xE3fFcA31BBA27392aF23B8018bd59c399f843093));

address sender;

string public constant ENV_PRIVATE_KEY = "PRIVATE_KEY";

function setUp() public {
mainnetFork = vm.createFork(vm.envString("MAINNET_RPC_URL"));
testnetFork = vm.createFork(vm.envString("TESTNET_RPC_URL"));

vm.selectFork(mainnetFork);

(SY, PT, YT) = IPMarket(market).readTokens();
mktState = market.readState(address(router));
timeToExpiry = mktState.expiry - block.timestamp;
}

function mintSY(uint256 amount) public {
console2.log("balance wsteth", IERC20(wstETH).balanceOf(sender));
IERC20(wstETH).approve(address(SY), type(uint256).max);
SY.deposit(sender, address(wstETH), amount, 1);
}

function mintPtYt(uint256 amount) public {
SY.transfer(address(YT), amount);
YT.mintPY(sender, sender);
}


function getPtExchangeRate(PYIndex index) public view returns (int256) {
(MarketState memory ms, MarketPreCompute memory mp) = getPendleMarketData(index);
return ms.totalPt._getExchangeRate(mp.totalAsset, mp.rateScalar, mp.rateAnchor, 0);
}

function getPendleMarketData(PYIndex index)
public
view
returns (MarketState memory ms, MarketPreCompute memory mp)
{
ms = market.readState(address(router));
mp = ms.getMarketPreCompute(index, block.timestamp);
}

function run() public {
uint256 pk = vm.envUint(ENV_PRIVATE_KEY);
sender = vm.addr(pk);

PYIndex mainnetIndex = YT.newIndex();

// compute optimal arbitrage to rmm pool
uint256 pendleRate = uint256(getPtExchangeRate(mainnetIndex));

vm.selectFork(testnetFork);
PYIndex index = YT.newIndex();
vm.startBroadcast(pk);

IERC20(wstETH).approve(address(rmm), type(uint256).max);
IERC20(SY).approve(address(rmm), type(uint256).max);
IERC20(PT).approve(address(rmm), type(uint256).max);
IERC20(YT).approve(address(rmm), type(uint256).max);

uint256 L = rmm.totalLiquidity();

PoolPreCompute memory comp = rmm.preparePoolPreCompute(index, block.timestamp);

uint256 rmmPrice = computeSpotPrice(comp.reserveInAsset, L, comp.strike_, rmm.sigma(), comp.tau_);

console2.log("rmmPrice: ", rmmPrice);
console2.log("pendleRate: ", pendleRate);
console2.log("asset reserve: ", comp.reserveInAsset);

if (pendleRate > rmmPrice) {
int256 dy = getDyGivenS(address(rmm), pendleRate, index);
console2.log("dy: ", dy);
uint256 amt = computeOptimalArbRaisePrice(address(rmm), pendleRate, uint256(dy), index);
console2.log("Amount to lower: ", amt);
mintSY(amt);
mintPtYt(rmm.SY().balanceOf(address(this)));
(uint256 amtOut, ) = rmm.swapExactPtForSy(amt, 0, address(this));
console2.log("amtOut: ", amtOut);
} else {
console2.log("lower!");
int256 dx = getDxGivenS(address(rmm), pendleRate, index);
console2.log("dx: ", dx);
uint256 amt = index.assetToSy(computeOptimalArbLowerPrice(address(rmm), pendleRate, uint256(dx), index));
mintSY(amt);
(uint256 amtOut, ) = rmm.swapExactSyForPt(amt, 0, address(this));
console2.log("amtOut: ", amtOut);
}

vm.stopBroadcast();
}
}
2 changes: 1 addition & 1 deletion script/DeployPool.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ contract DeployPool is Script {
address public constant PT_ADDRESS = address(0);
uint256 public constant fee = 0.0002 ether;
address public constant curator = address(0);
Factory FACTORY = Factory(0xA61D6761ce83F1A2E3B128B7a5033e99BcdAa7d5);
Factory FACTORY = Factory(0x8aB8D2d0648Bf1DFeD438540F46eaD7542820BeB);
IPMarket market = IPMarket(0xC374f7eC85F8C7DE3207a10bB1978bA104bdA3B2);
IPAllActionV3 router = IPAllActionV3(0x00000000005BBB0EF59571E58418F9a4357b68A0);
address wstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0; //real wsteth
Expand Down
Loading