orderlib uses reverts instead of returned errors; Dexorder.sol

This commit is contained in:
Tim Olson
2023-10-18 16:18:14 -04:00
parent 7c79e9f98e
commit 510aede125
7 changed files with 90 additions and 72 deletions

View File

@@ -5,6 +5,7 @@ import "forge-std/Script.sol";
import "forge-std/console2.sol"; import "forge-std/console2.sol";
import "../src/QueryHelper.sol"; import "../src/QueryHelper.sol";
import "../src/Factory.sol"; import "../src/Factory.sol";
import "../src/Dexorder.sol";
import "../test/MockEnv.sol"; import "../test/MockEnv.sol";
contract Deploy is Script { contract Deploy is Script {
@@ -13,12 +14,15 @@ contract Deploy is Script {
vm.startBroadcast(deployerPrivateKey); vm.startBroadcast(deployerPrivateKey);
Factory deployer = new Factory{salt:keccak256(abi.encode(1))}(); Factory deployer = new Factory{salt:keccak256(abi.encode(1))}();
QueryHelper query = new QueryHelper(); QueryHelper query = new QueryHelper();
Dexorder dexorder = new Dexorder();
MockEnv mock = new MockEnv(); MockEnv mock = new MockEnv();
vm.stopBroadcast(); vm.stopBroadcast();
console2.log('VaultDeployer'); console2.log('VaultDeployer');
console2.log(address(deployer)); console2.log(address(deployer));
console2.log('QueryHelper'); console2.log('QueryHelper');
console2.log(address(query)); console2.log(address(query));
console2.log('Dexorder');
console2.log(address(dexorder));
console2.log('MockEnv'); // todo no mock in production deployment console2.log('MockEnv'); // todo no mock in production deployment
console2.log(address(mock)); console2.log(address(mock));
} }

View File

@@ -17,6 +17,6 @@ library Constants {
// Swap statuses // Swap statuses
string internal constant SWAP_OK = ''; // fastest comparison bytes32 internal constant SWAP_OK = ''; // fastest comparison
// other errors may be passed through from Uniswap // other errors may be passed through from Uniswap
} }

45
src/Dexorder.sol Normal file
View File

@@ -0,0 +1,45 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;
import "./OrderLib.sol";
import "./Vault.sol";
pragma abicoder v2;
contract Dexorder {
// represents the Dexorder organization
event DexorderExecutions(uint128 indexed id, bytes[] errors);
struct ExecutionRequest {
address payable vault;
uint64 orderIndex;
uint8 trancheIndex;
OrderLib.PriceProof proof;
}
function execute( uint128 id, ExecutionRequest memory req ) public returns (bytes memory error) {
error = _execute(req);
bytes[] memory errors = new bytes[](1);
errors[0] = error;
emit DexorderExecutions(id, errors);
}
function execute( uint128 id, ExecutionRequest[] memory reqs ) public returns (bytes[] memory errors) {
errors = new bytes[](reqs.length);
for( uint8 i=0; i<reqs.length; i++ )
errors[i] = _execute(reqs[i]);
emit DexorderExecutions(id, errors);
}
function _execute( ExecutionRequest memory req ) private returns (bytes memory error) {
// single tranche execution
try Vault(req.vault).execute(req.orderIndex, req.trancheIndex, req.proof) {
return '';
}
catch (bytes memory reason) {
return reason;
}
}
}

View File

@@ -131,19 +131,15 @@ library OrderLib {
} }
function _placeOrder(OrdersInfo storage self, SwapOrder memory order) internal { function _placeOrder(OrdersInfo storage self, SwapOrder memory order) internal {
console2.log('OrderLib._placeOrder()');
SwapOrder[] memory orders = new SwapOrder[](1); SwapOrder[] memory orders = new SwapOrder[](1);
orders[0] = order; orders[0] = order;
return _placeOrders(self,orders,OcoMode.NO_OCO); return _placeOrders(self,orders,OcoMode.NO_OCO);
} }
function _placeOrders(OrdersInfo storage self, SwapOrder[] memory orders, OcoMode ocoMode) internal { function _placeOrders(OrdersInfo storage self, SwapOrder[] memory orders, OcoMode ocoMode) internal {
console2.log('_placeOrders A');
require(orders.length < type(uint8).max); require(orders.length < type(uint8).max);
console2.log('_placeOrders B');
uint64 startIndex = uint64(self.orders.length); uint64 startIndex = uint64(self.orders.length);
require(startIndex < type(uint64).max); require(startIndex < type(uint64).max);
console2.log('_placeOrders C');
uint64 ocoGroup; uint64 ocoGroup;
if( ocoMode == OcoMode.NO_OCO ) if( ocoMode == OcoMode.NO_OCO )
ocoGroup = NO_OCO_INDEX; ocoGroup = NO_OCO_INDEX;
@@ -153,11 +149,9 @@ library OrderLib {
} }
else else
revert('OCOM'); revert('OCOM');
console2.log('_placeOrders D');
for( uint8 o = 0; o < orders.length; o++ ) { for( uint8 o = 0; o < orders.length; o++ ) {
SwapOrder memory order = orders[o]; SwapOrder memory order = orders[o];
require(order.route.exchange == Exchange.UniswapV3, 'UR'); require(order.route.exchange == Exchange.UniswapV3, 'UR');
console2.log('_placeOrders E');
// todo more order validation // todo more order validation
// we must explicitly copy into storage because Solidity doesn't implement copying the double-nested // we must explicitly copy into storage because Solidity doesn't implement copying the double-nested
// tranches constraints array :( // tranches constraints array :(
@@ -171,7 +165,6 @@ library OrderLib {
status.order.route = order.route; status.order.route = order.route;
status.order.chainOrder = order.chainOrder; status.order.chainOrder = order.chainOrder;
status.order.outputDirectlyToOwner = order.outputDirectlyToOwner; status.order.outputDirectlyToOwner = order.outputDirectlyToOwner;
console2.log('_placeOrders F');
for( uint t=0; t<order.tranches.length; t++ ) { for( uint t=0; t<order.tranches.length; t++ ) {
status.order.tranches.push(); status.order.tranches.push();
OrderLib.Tranche memory ot = order.tranches[t]; // order tranche OrderLib.Tranche memory ot = order.tranches[t]; // order tranche
@@ -179,22 +172,18 @@ library OrderLib {
st.fraction = ot.fraction; st.fraction = ot.fraction;
for( uint c=0; c<ot.constraints.length; c++ ) for( uint c=0; c<ot.constraints.length; c++ )
st.constraints.push(ot.constraints[c]); st.constraints.push(ot.constraints[c]);
console2.log('_placeOrders G');
status.trancheFilledIn.push(0); status.trancheFilledIn.push(0);
status.trancheFilledOut.push(0); status.trancheFilledOut.push(0);
} }
status.state = SwapOrderState.Open; status.state = SwapOrderState.Open;
status.start = uint32(block.timestamp); status.start = uint32(block.timestamp);
status.ocoGroup = ocoGroup; status.ocoGroup = ocoGroup;
console2.log('_placeOrders H');
} }
emit DexorderSwapPlaced(startIndex,uint8(orders.length)); emit DexorderSwapPlaced(startIndex,uint8(orders.length));
} }
// return codes: // revert codes:
//
// returns the zero-length string '' on success
// //
// NO order is not open // NO order is not open
// OCO order was implicitly canceled by an OCO // OCO order was implicitly canceled by an OCO
@@ -202,12 +191,10 @@ library OrderLib {
// TE current time is too early for this tranche // TE current time is too early for this tranche
// TL current time is too late for this tranche // TL current time is too late for this tranche
// //
function execute(OrdersInfo storage self, uint64 orderIndex, uint8 tranche_index, PriceProof memory proof) internal function execute(OrdersInfo storage self, address owner, uint64 orderIndex, uint8 tranche_index, PriceProof memory proof) internal {
returns (string memory error)
{
SwapOrderStatus storage status = self.orders[orderIndex]; SwapOrderStatus storage status = self.orders[orderIndex];
if (status.state != SwapOrderState.Open) if (status.state != SwapOrderState.Open)
return 'NO'; // Not Open revert('NO'); // Not Open
Tranche storage tranche = status.order.tranches[tranche_index]; Tranche storage tranche = status.order.tranches[tranche_index];
uint160 sqrtPriceX96 = 0; uint160 sqrtPriceX96 = 0;
uint160 sqrtPriceLimitX96 = 0; uint160 sqrtPriceLimitX96 = 0;
@@ -219,10 +206,10 @@ library OrderLib {
TimeConstraint memory tc = abi.decode(constraint.constraint, (TimeConstraint)); TimeConstraint memory tc = abi.decode(constraint.constraint, (TimeConstraint));
uint32 time = tc.earliest.mode == TimeMode.Timestamp ? tc.earliest.time : status.start + tc.earliest.time; uint32 time = tc.earliest.mode == TimeMode.Timestamp ? tc.earliest.time : status.start + tc.earliest.time;
if (time > block.timestamp) if (time > block.timestamp)
return 'TE'; // time early revert('TE'); // time early
time = tc.latest.mode == TimeMode.Timestamp ? tc.latest.time : status.start + tc.latest.time; time = tc.latest.mode == TimeMode.Timestamp ? tc.latest.time : status.start + tc.latest.time;
if (time < block.timestamp) if (time < block.timestamp)
return 'TL'; // time late revert('TL'); // time late
} }
else if (constraint.mode == ConstraintMode.Limit) { else if (constraint.mode == ConstraintMode.Limit) {
if( sqrtPriceX96 == 0 ) { if( sqrtPriceX96 == 0 ) {
@@ -233,20 +220,19 @@ library OrderLib {
if( pc.isRatio ) if( pc.isRatio )
pc.valueSqrtX96 = uint160(price * pc.valueSqrtX96 / 2**96); // todo overflow check! pc.valueSqrtX96 = uint160(price * pc.valueSqrtX96 / 2**96); // todo overflow check!
if( pc.isAbove && price < pc.valueSqrtX96 || !pc.isAbove && price > pc.valueSqrtX96 ) if( pc.isAbove && price < pc.valueSqrtX96 || !pc.isAbove && price > pc.valueSqrtX96 )
return 'L'; revert('L');
} }
else if (constraint.mode == ConstraintMode.Barrier) { else if (constraint.mode == ConstraintMode.Barrier) {
return 'NI'; // not implemented revert('NI'); // not implemented
} }
else if (constraint.mode == ConstraintMode.Trailing) { else if (constraint.mode == ConstraintMode.Trailing) {
return 'NI'; // not implemented revert('NI'); // not implemented
} }
else if (constraint.mode == ConstraintMode.Line) { else if (constraint.mode == ConstraintMode.Line) {
return 'NI'; // not implemented revert('NI'); // not implemented
} }
else else // unknown constraint
return 'NI'; // not implemented revert('NI'); // not implemented
// unknown constraint
} }
uint256 amount = status.order.amount * tranche.fraction / type(uint16).max // the most this tranche could do uint256 amount = status.order.amount * tranche.fraction / type(uint16).max // the most this tranche could do
- (status.order.amountIsInput ? status.trancheFilledIn[tranche_index] : status.trancheFilledOut[tranche_index]); // minus tranche fills - (status.order.amountIsInput ? status.trancheFilledIn[tranche_index] : status.trancheFilledOut[tranche_index]); // minus tranche fills
@@ -254,42 +240,39 @@ library OrderLib {
uint256 remaining = status.order.amount - (status.order.amountIsInput ? status.filledIn : status.filledOut); uint256 remaining = status.order.amount - (status.order.amountIsInput ? status.filledIn : status.filledOut);
if (amount > remaining) // not more than the order's overall remaining amount if (amount > remaining) // not more than the order's overall remaining amount
amount = remaining; amount = remaining;
address recipient = status.order.outputDirectlyToOwner ? owner : address(this);
uint256 amountIn; uint256 amountIn;
uint256 amountOut; uint256 amountOut;
if( status.order.route.exchange == Exchange.UniswapV3 ) if( status.order.route.exchange == Exchange.UniswapV3 )
(error, amountIn, amountOut) = _do_execute_univ3(status.order, pool, amount, sqrtPriceLimitX96); (amountIn, amountOut) = _do_execute_univ3(recipient, status.order, pool, amount, sqrtPriceLimitX96);
// todo other routes // todo other routes
else else
return 'UR'; // unknown route revert('UR'); // unknown route
if( bytes(error).length == 0 ) { status.filledIn += amountIn;
status.filledIn += amountIn; status.filledOut += amountOut;
status.filledOut += amountOut; status.trancheFilledIn[tranche_index] += amountIn;
status.trancheFilledIn[tranche_index] += amountIn; status.trancheFilledOut[tranche_index] += amountOut;
status.trancheFilledOut[tranche_index] += amountOut; emit DexorderSwapFilled(orderIndex, tranche_index, amountIn, amountOut);
emit DexorderSwapFilled(orderIndex, tranche_index, amountIn, amountOut); _checkCompleted(self, orderIndex, status);
_checkCompleted(self, orderIndex, status);
}
return ''; // success is no error, said no one
} }
function _do_execute_univ3( SwapOrder storage order, address pool, uint256 amount, uint160 sqrtPriceLimitX96) private function _do_execute_univ3( address recipient, SwapOrder storage order, address pool, uint256 amount, uint160 sqrtPriceLimitX96) private
returns (string memory error, uint256 amountIn, uint256 amountOut) returns (uint256 amountIn, uint256 amountOut)
{ {
// todo refactor this signature to be more low-level, taking only the in/out amounts and limit prices. doesnt need self/status/index // todo refactor this signature to be more low-level, taking only the in/out amounts and limit prices. doesnt need self/status/index
if (sqrtPriceLimitX96 == 0) if (sqrtPriceLimitX96 == 0)
// check pool inversion to see if the price should be high or low // check pool inversion to see if the price should be high or low
sqrtPriceLimitX96 = order.tokenIn < order.tokenOut ? 0 : type(uint160).max; sqrtPriceLimitX96 = order.tokenIn < order.tokenOut ? 0 : type(uint160).max;
// todo swap direct to owner
if (order.amountIsInput) { if (order.amountIsInput) {
amountIn = amount; amountIn = amount;
(error, amountOut) = UniswapSwapper.swapExactInput(UniswapSwapper.SwapParams( amountOut = UniswapSwapper.swapExactInput(UniswapSwapper.SwapParams(
pool, order.tokenIn, order.tokenOut, order.route.fee, amount, sqrtPriceLimitX96)); pool, order.tokenIn, order.tokenOut, recipient, order.route.fee, amount, sqrtPriceLimitX96));
} }
else { else {
amountOut = amount; amountOut = amount;
(error, amountIn) = UniswapSwapper.swapExactOutput(UniswapSwapper.SwapParams( amountIn = UniswapSwapper.swapExactOutput(UniswapSwapper.SwapParams(
pool, order.tokenIn, order.tokenOut, order.route.fee, amount, sqrtPriceLimitX96)); pool, order.tokenIn, order.tokenOut, recipient, order.route.fee, amount, sqrtPriceLimitX96));
} }
} }

View File

@@ -12,12 +12,13 @@ library UniswapSwapper {
address pool; address pool;
address tokenIn; address tokenIn;
address tokenOut; address tokenOut;
address recipient;
uint24 fee; uint24 fee;
uint256 amount; uint256 amount;
uint160 sqrtPriceLimitX96; uint160 sqrtPriceLimitX96;
} }
function swapExactInput(SwapParams memory params) internal returns (string memory error, uint256 amountOut) function swapExactInput(SwapParams memory params) internal returns (uint256 amountOut)
{ {
// struct ExactInputSingleParams { // struct ExactInputSingleParams {
// address tokenIn; // address tokenIn;
@@ -29,22 +30,13 @@ library UniswapSwapper {
// uint256 amountOutMinimum; // uint256 amountOutMinimum;
// uint160 sqrtPriceLimitX96; // uint160 sqrtPriceLimitX96;
// } // }
return Constants.uniswapV3SwapRouter.exactInputSingle(ISwapRouter.ExactInputSingleParams({
try Constants.uniswapV3SwapRouter.exactInputSingle(ISwapRouter.ExactInputSingleParams({ tokenIn: params.tokenIn, tokenOut: params.tokenOut, fee: params.fee, recipient: params.recipient,
tokenIn: params.tokenIn, tokenOut: params.tokenOut, fee: params.fee, recipient: address(this), // todo return directly to wallet?
deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: 0, sqrtPriceLimitX96: params.sqrtPriceLimitX96 deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: 0, sqrtPriceLimitX96: params.sqrtPriceLimitX96
})) returns (uint256 filledOut) { }));
amountOut = filledOut;
error = Constants.SWAP_OK;
}
catch Error(string memory reason) {
amountOut = 0;
error = reason;
}
} }
function swapExactOutput(SwapParams memory params) internal returns (uint256 amountIn)
function swapExactOutput(SwapParams memory params) internal returns (string memory error, uint256 amountIn)
{ {
// struct ExactOutputSingleParams { // struct ExactOutputSingleParams {
// address tokenIn; // address tokenIn;
@@ -60,20 +52,13 @@ library UniswapSwapper {
uint256 balance = IERC20(params.tokenIn).balanceOf(t); uint256 balance = IERC20(params.tokenIn).balanceOf(t);
if( balance == 0 ) { if( balance == 0 ) {
// todo dust? // todo dust?
return ('IIA', 0); revert('IIA');
} }
try Constants.uniswapV3SwapRouter.exactOutputSingle(ISwapRouter.ExactOutputSingleParams({ return Constants.uniswapV3SwapRouter.exactOutputSingle(ISwapRouter.ExactOutputSingleParams({
tokenIn: params.tokenIn, tokenOut: params.tokenOut, fee: params.fee, recipient: t, // todo return directly to wallet? tokenIn: params.tokenIn, tokenOut: params.tokenOut, fee: params.fee, recipient: params.recipient,
deadline: block.timestamp, amountOut: params.amount, amountInMaximum: balance, // todo use only the committed allocation? deadline: block.timestamp, amountOut: params.amount, amountInMaximum: balance, // todo use only the committed allocation?
sqrtPriceLimitX96: params.sqrtPriceLimitX96 sqrtPriceLimitX96: params.sqrtPriceLimitX96
})) returns (uint256 filledIn) { }));
amountIn = filledIn;
error = Constants.SWAP_OK;
}
catch Error(string memory reason) {
amountIn = 0;
error = reason;
}
} }
} }

View File

@@ -10,6 +10,8 @@ import "forge-std/console2.sol";
contract Vault { contract Vault {
// represents the interests of its owner client
using OrderLib for OrderLib.OrdersInfo; using OrderLib for OrderLib.OrdersInfo;
uint8 public immutable version; uint8 public immutable version;
@@ -67,9 +69,8 @@ contract Vault {
} }
function execute(uint64 orderIndex, uint8 tranche_index, OrderLib.PriceProof memory proof) public function execute(uint64 orderIndex, uint8 tranche_index, OrderLib.PriceProof memory proof) public
returns (string memory error)
{ {
return orderList.execute(orderIndex, tranche_index, proof); orderList.execute(owner, orderIndex, tranche_index, proof);
} }
modifier onlyOwner() { modifier onlyOwner() {

View File

@@ -10,7 +10,7 @@ library VaultAddress {
// keccak-256 hash of the Vault's bytecode (not the deployed bytecode but the initialization bytecode) // keccak-256 hash of the Vault's bytecode (not the deployed bytecode but the initialization bytecode)
// can paste into: // can paste into:
// https://emn178.github.io/online-tools/keccak_256.html // https://emn178.github.io/online-tools/keccak_256.html
bytes32 internal constant VAULT_INIT_CODE_HASH = 0x3c95480d723e6cf3e130cfb53bfa2f15bd0bfc628246f77dfabe64ff943af969; bytes32 internal constant VAULT_INIT_CODE_HASH = 0x94dd1e2fe4a67770f9295aff1b352fb0792647d2377cd96aa72e4c3a3222aad1;
// the contract being constructed must not have any constructor arguments or the determinism will be broken. instead, use a callback to // the contract being constructed must not have any constructor arguments or the determinism will be broken. instead, use a callback to
// get construction arguments // get construction arguments