Skip to content

Commit

Permalink
initial build
Browse files Browse the repository at this point in the history
  • Loading branch information
josojo authored and Nicholas Rodrigues Lordello committed Sep 23, 2020
0 parents commit ae43932
Show file tree
Hide file tree
Showing 13 changed files with 9,708 additions and 0 deletions.
430 changes: 430 additions & 0 deletions .eslintrc.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.sol linguist-language=Solidity
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build
node_modules
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2018 Truffle

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

## One Block Auctions (OBA):

To run the project execute:

```
yarn
docker pull ethereum/solc:0.6.12
yarn build
```

To run test
```
yarn ganache
yarn test
```
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "test",
"scripts": {
"build": "waffle",
"test": "export NODE_ENV=test && mocha -r ts-node/register 'test/**/*.ts'",
"btest": "yarn run build && yarn run test",
"lint": "eslint '{src,test}/**/*.ts'",
"lint:fix": "eslint --fix '{src,test}/**/*.ts'",
"ganache": "ganache-cli --host 0.0.0.0 --gasLimit 12e6 --deterministic"
},
"dependencies": {
"bn.js": "^5.1.3",
"ethereumjs-abi": "^0.6.8",
"ethereumjs-util": "^7.0.5",
"ethers": "5.0.12"
},
"devDependencies": {
"@ethereum-waffle/mock-contract": "^3.1.0",
"@openzeppelin/contracts": "^2.5.0",
"@types/chai": "^4.2.3",
"@types/mocha": "^5.2.7",
"@typescript-eslint/eslint-plugin": "^2.30.0",
"@typescript-eslint/parser": "^2.30.0",
"@uniswap/v2-core": "^1.0.1",
"chai": "^4.2.0",
"eslint": "^6.8.0",
"eslint-plugin-import": "^2.20.2",
"ethereum-waffle": "^3.1.0",
"mocha": "^8.1.3",
"prettier": "^2.1.1",
"ts-node": "^8.9.1",
"typescript": "^3.8.3"
}
}
252 changes: 252 additions & 0 deletions src/contracts/PreAMMBatcher.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
pragma experimental ABIEncoderV2;
pragma solidity ^0.5.16;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v2-core/contracts/libraries/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";

contract PreAMMBatcher {
using SafeMath for uint256;
IUniswapV2Factory uniswapFactory;

bytes32 public constant DOMAIN_SEPARATOR = keccak256("preBatcher-V1");
mapping(address => uint8) public nonces; // probably a nonce per tokenpair would be better

struct Order {
uint256 sellAmount;
uint256 buyAmount;
address sellToken;
address buyToken;
address owner;
}

struct Fraction {
uint256 numerator;
uint256 denominator;
}

event BatchSettlement(
address token0,
address token1,
uint256 sellAmountToken0,
uint256 sellAmountToken1
);

constructor(IUniswapV2Factory _uniswapFactory) public {
uniswapFactory = _uniswapFactory;
}

function preBatchTrade(bytes memory order0bytes, bytes memory order1bytes)
public
returns (Fraction memory clearingPrice)
{
Order memory sellOrderToken0 = parseOrderBytes(order0bytes);
Order memory sellOrderToken1 = parseOrderBytes(order1bytes);
require(
orderChecks(sellOrderToken0, sellOrderToken1),
"orders-checks are not succesful"
);
receiveTradeAmounts(sellOrderToken0, sellOrderToken1);
IUniswapV2Pair uniswapPool = IUniswapV2Pair(
uniswapFactory.getPair(
sellOrderToken0.sellToken,
sellOrderToken1.sellToken
)
);
clearingPrice = calculateSettlementPrice(
sellOrderToken0,
sellOrderToken1,
uniswapPool
);
uint256 unmatchedAmountToken0 = sellOrderToken0.sellAmount.sub(
sellOrderToken1.sellAmount.mul(clearingPrice.numerator).div(
clearingPrice.denominator
)
);
settleUnmatchedAmountsToUniswap(
unmatchedAmountToken0,
clearingPrice,
sellOrderToken0,
uniswapPool
);
payOutTradeProceedings(sellOrderToken0, sellOrderToken1);
emit BatchSettlement(
sellOrderToken0.sellToken,
sellOrderToken1.sellToken,
sellOrderToken0.sellAmount.sub(unmatchedAmountToken0),
sellOrderToken1.sellAmount
);
}

function orderChecks(
Order memory sellOrderToken0,
Order memory sellOrderToken1
) public pure returns (bool) {
// later the signature verification should happen here as well
return
sellOrderToken0.sellToken == sellOrderToken1.buyToken &&
sellOrderToken1.sellToken == sellOrderToken0.buyToken;
}

function parseOrderBytes(bytes memory orderBytes)
public
returns (Order memory order)
{
(
uint256 sellAmount,
uint256 buyAmount,
address sellToken,
address buyToken,
address owner,
uint8 nonce,
uint8 v,
bytes32 r,
bytes32 s
) = abi.decode(
orderBytes,
(
uint256,
uint256,
address,
address,
address,
uint8,
uint8,
bytes32,
bytes32
)
);
bytes32 digest = keccak256(
abi.encode(
DOMAIN_SEPARATOR,
sellAmount,
buyAmount,
sellToken,
buyToken,
owner,
nonce
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"invalid_signature"
);
require(nonces[owner] < nonce, "nonce already used");
nonces[owner] = nonce;
order = Order({
sellAmount: sellAmount,
buyAmount: buyAmount,
buyToken: buyToken,
sellToken: sellToken,
owner: owner
});
}

function calculateSettlementPrice(
Order memory sellOrderToken0,
Order memory sellOrderToken1,
IUniswapV2Pair uniswapPool
) public view returns (Fraction memory clearingPrice) {
(uint112 reserve0, uint112 reserve1, ) = uniswapPool.getReserves();
uint256 uniswapK = uint256(reserve0).mul(reserve1);
// if deltaUniswapToken0 will be > 0
// if(sellOrderToken1.sellAmount * serve0 / reserve1 > sellToken2Order.sellAmount)
uint256 p = uniswapK.div(
uint256(2).mul(uint256(reserve1).add(sellOrderToken1.sellAmount))
);
uint256 newReserve0 = p.add(
Math.sqrt(
p.mul(p).add(
uniswapK.mul(sellOrderToken0.sellAmount).div(
uint256(reserve1).add(sellOrderToken1.sellAmount)
)
)
)
);
uint256 newReserve1 = uniswapK.div(newReserve0);
clearingPrice = Fraction({
numerator: newReserve0,
denominator: newReserve1
});
require(
clearingPrice.numerator.mul(sellOrderToken0.sellAmount) >=
clearingPrice.denominator.mul(sellOrderToken0.buyAmount),
"sellOrderToken0 price violations"
);
require(
clearingPrice.numerator.mul(sellOrderToken1.sellAmount) >
clearingPrice.denominator.mul(sellOrderToken1.buyAmount),
"sellOrderToken1 price violations"
);
}

function settleUnmatchedAmountsToUniswap(
uint256 unsettledDirectAmountToken0,
Fraction memory clearingPrice,
Order memory sellOrderToken0,
IUniswapV2Pair uniswapPool
) internal {
require(
IERC20(sellOrderToken0.sellToken).transfer(
address(uniswapPool),
unsettledDirectAmountToken0
),
"transfer to uniswap failed"
);
uniswapPool.swap(
0,
unsettledDirectAmountToken0
.mul(clearingPrice.denominator)
.mul(997)
.div(clearingPrice.numerator)
.div(1000),
address(this),
""
);
}

function receiveTradeAmounts(
Order memory sellOrderToken0,
Order memory sellOrderToken1
) internal {
require(
IERC20(sellOrderToken0.sellToken).transferFrom(
sellOrderToken0.owner,
address(this),
sellOrderToken0.sellAmount
),
"transferFrom for token0 was not succesful"
);
require(
IERC20(sellOrderToken1.sellToken).transferFrom(
sellOrderToken1.owner,
address(this),
sellOrderToken1.sellAmount
),
"transferFrom for token1 was not succesful"
);
}

function payOutTradeProceedings(
Order memory sellOrderToken0,
Order memory sellOrderToken1
) internal {
require(
IERC20(sellOrderToken0.sellToken).transfer(
sellOrderToken1.owner,
IERC20(sellOrderToken0.sellToken).balanceOf(address(this))
),
"final token transfer failed"
);
require(
IERC20(sellOrderToken0.buyToken).transfer(
sellOrderToken0.owner,
IERC20(sellOrderToken0.buyToken).balanceOf(address(this))
),
"final token1 transfer failed"
);
}
}
44 changes: 44 additions & 0 deletions src/js/orders.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

import BN from 'bn.js';
const abi = require('ethereumjs-abi');
import {utils, Wallet} from 'ethers';
import {ecsign} from 'ethereumjs-util';

const DOMAIN_SEPARATOR = '0x24a654ed47680d6a76f087ec92b3a0f0fe4c9c82c26bff3bb22dffe0f120c7f0';

export class Order {
sellAmount: BN;
buyAmount: BN;
sellToken: string;
buyToken: string;
wallet: Wallet;
nonce: BN;

constructor(sellAmount: BN | number, buyAmount: BN | number, sellToken: string,
buyToken: string, wallet: Wallet, nonce: BN | number) {
this.sellAmount = new BN(sellAmount);
this.buyAmount = new BN(buyAmount);
this.sellToken = sellToken;
this.buyToken = buyToken;
this.wallet = wallet;
this.nonce = new BN(nonce);
}

encode(): string {
const digest = this.getOrderDigest();
const {v, r, s} = ecsign(Buffer.from(digest.slice(2), 'hex'), Buffer.from(this.wallet.privateKey.slice(2), 'hex'));
return abi.rawEncode(['uint256', 'uint256', 'address', 'address',
'address', 'uint8', 'uint8', 'bytes32', 'bytes32'],
[this.sellAmount.toString(), this.buyAmount.toString(), this.sellToken, this.buyToken,
this.wallet.address, this.nonce.toString(), v, utils.hexlify(r), utils.hexlify(s)]);
}

getOrderDigest(): string {
return utils.keccak256(
utils.defaultAbiCoder.encode(
['bytes32', 'uint256', 'uint256', 'address', 'address', 'address', 'uint8'],
[DOMAIN_SEPARATOR, this.sellAmount.toString(), this.buyAmount.toString(), this.sellToken,
this.buyToken, this.wallet.address, this.nonce.toString()]
));
}
}
Loading

0 comments on commit ae43932

Please sign in to comment.