Skip to content

Instantly share code, notes, and snippets.

@justinbarry
Created September 26, 2020 00:12
Show Gist options
  • Save justinbarry/9f9327736a1505873ff981d73d246c57 to your computer and use it in GitHub Desktop.
Save justinbarry/9f9327736a1505873ff981d73d246c57 to your computer and use it in GitHub Desktop.
pragma solidity 0.5.15;
contract IAugur {
function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function isKnownUniverse(IUniverse _universe) public view returns (bool);
function trustedCashTransfer(address _from, address _to, uint256 _amount) public returns (bool);
function isTrustedSender(address _address) public returns (bool);
function onCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool);
function onYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool);
function onScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool);
function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool);
function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool);
function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool);
function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool);
function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool);
function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool);
function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool);
function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool);
function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool);
function logTradingProceedsClaimed(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool);
function logUniverseForked(IMarket _forkingMarket) public returns (bool);
function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logShareTokensBalanceChanged(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool);
function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool);
function logTimestampSet(uint256 _newTimestamp) public returns (bool);
function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool);
function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool);
function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logMarketRepBondTransferred(address _universe, address _from, address _to) public returns (bool);
function logWarpSyncDataUpdated(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool);
function isKnownFeeSender(address _feeSender) public view returns (bool);
function lookup(bytes32 _key) public view returns (address);
function getTimestamp() public view returns (uint256);
function getMaximumMarketEndDate() public returns (uint256);
function isKnownMarket(IMarket _market) public view returns (bool);
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32);
function logValidityBondChanged(uint256 _validityBond) public returns (bool);
function logDesignatedReportStakeChanged(uint256 _designatedReportStake) public returns (bool);
function logNoShowBondChanged(uint256 _noShowBond) public returns (bool);
function logReportingFeeChanged(uint256 _reportingFee) public returns (bool);
function getUniverseForkIndex(IUniverse _universe) public view returns (uint256);
function getMarketType(IMarket _market) public view returns (IMarket.MarketType);
function getMarketOutcomes(IMarket _market) public view returns (bytes32[] memory _outcomes);
}
contract IOwnable {
function getOwner() public view returns (address);
function transferOwnership(address _newOwner) public returns (bool);
}
contract ITyped {
function getTypeName() public view returns (bytes32);
}
library SafeMathInt256 {
// Signed ints with n bits can range from -2**(n-1) to (2**(n-1) - 1)
int256 private constant INT256_MIN = -2**(255);
int256 private constant INT256_MAX = (2**(255) - 1);
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
// No need to check for dividing by 0 -- Solidity automatically throws on division by 0
int256 c = a / b;
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
require(((a >= 0) && (b >= a - INT256_MAX)) || ((a < 0) && (b <= a - INT256_MIN)));
return a - b;
}
function add(int256 a, int256 b) internal pure returns (int256) {
require(((a >= 0) && (b <= INT256_MAX - a)) || ((a < 0) && (b >= INT256_MIN - a)));
return a + b;
}
function min(int256 a, int256 b) internal pure returns (int256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(int256 a, int256 b) internal pure returns (int256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function abs(int256 a) internal pure returns (int256) {
if (a < 0) {
return -a;
}
return a;
}
function getInt256Min() internal pure returns (int256) {
return INT256_MIN;
}
function getInt256Max() internal pure returns (int256) {
return INT256_MAX;
}
// Float [fixed point] Operations
function fxpMul(int256 a, int256 b, int256 base) internal pure returns (int256) {
return div(mul(a, b), base);
}
function fxpDiv(int256 a, int256 b, int256 base) internal pure returns (int256) {
return div(mul(a, base), b);
}
function sqrt(int256 y) internal pure returns (int256 z) {
if (y > 3) {
int256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
library SafeMathUint256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function subS(uint256 a, uint256 b, string memory message) internal pure returns (uint256) {
require(b <= a, message);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function getUint256Min() internal pure returns (uint256) {
return 0;
}
function getUint256Max() internal pure returns (uint256) {
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) {
return a % b == 0;
}
// Float [fixed point] Operations
function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, base), b);
}
}
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string value,
uint256 indexed id
);
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @notice Get the total supply of a Token.
/// @param id ID of the Token
/// @return The total supply of the Token type requested
function totalSupply(uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return The _owner's balance of the Token types requested
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _account) public view returns (uint256) {
return balances[_account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address _recipient, uint256 _amount) public returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address _spender, uint256 _amount) public returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, allowances[_sender][msg.sender].sub(_amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
_approve(msg.sender, _spender, allowances[msg.sender][_spender].add(_addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
_approve(msg.sender, _spender, allowances[msg.sender][_spender].sub(_subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
balances[_sender] = balances[_sender].sub(_amount);
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
onTokenTransfer(_sender, _recipient, _amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].sub(_amount);
totalSupply = totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address _owner, address _spender, uint256 _amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address _account, uint256 _amount) internal {
_burn(_account, _amount);
_approve(_account, msg.sender, allowances[_account][msg.sender].sub(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function onTokenTransfer(address _from, address _to, uint256 _value) internal;
}
contract AMMExchange is ERC20 {
using SafeMathUint256 for uint256;
using SafeMathInt256 for int256;
ICash public cash;
IParaShareToken public shareToken;
IMarket public augurMarket;
uint256 public numTicks;
uint256 public INVALID;
uint256 public NO;
uint256 public YES;
uint256 public fee; // [0-1000] how many thousandths of swaps should be kept as fees
function initialize(IMarket _market, IParaShareToken _shareToken, uint256 _fee) public {
require(cash == ICash(0)); // can only initialize once
require(_fee <= 1000); // fee must be [0,1000]
cash = _shareToken.cash();
shareToken = _shareToken;
augurMarket = _market;
numTicks = _market.getNumTicks();
cash.approve(address(_shareToken), 2**256-1);
cash.approve(address(_shareToken.augur()), 2**256-1);
INVALID = _shareToken.getTokenId(_market, 0);
NO = _shareToken.getTokenId(_market, 1);
YES = _shareToken.getTokenId(_market, 2);
fee = _fee;
}
// Adds shares to the liquidity pool by minting complete sets.
function addLiquidity(uint256 _setsToBuy) public {
uint256 _lpTokensGained = rateAddLiquidity(_setsToBuy, _setsToBuy);
cash.transferFrom(msg.sender, address(this), _setsToBuy.mul(numTicks));
shareToken.publicBuyCompleteSets(augurMarket, _setsToBuy);
_mint(msg.sender, _lpTokensGained);
}
// Add shares to the liquidity pool by minting complete sets...
// But then swap away some of those shares for the opposed shares.
function addLiquidityThenSwap(uint256 _setsToBuy, bool _swapForYes, uint256 _swapHowMuch) external {
uint256 _lpTokensGained = rateAddLiquidityThenSwap(_setsToBuy, _swapForYes, _swapHowMuch);
cash.transferFrom(msg.sender, address(this), _setsToBuy.mul(numTicks));
shareToken.publicBuyCompleteSets(augurMarket, _setsToBuy);
_mint(msg.sender, _lpTokensGained);
}
// returns how many LP tokens you get for providing the given number of sets
function rateAddLiquidity(uint256 _yesses, uint256 _nos) public view returns (uint256) {
uint256 _yesBalance = shareToken.balanceOf(address(this), YES);
uint256 _noBalance = shareToken.balanceOf(address(this), NO);
uint256 _priorLiquidityConstant = SafeMathUint256.sqrt(_yesBalance * _noBalance);
uint256 _newLiquidityConstant = SafeMathUint256.sqrt((_yesBalance + _yesses) * (_noBalance + _nos));
if (_priorLiquidityConstant == 0) {
return _newLiquidityConstant;
} else {
uint256 _totalSupply = totalSupply;
return _totalSupply.mul(_newLiquidityConstant).div(_priorLiquidityConstant).sub(_totalSupply);
}
}
function rateAddLiquidityThenSwap(uint256 _setsToBuy, bool _swapForYes, uint256 _swapHowMuch) public view returns (uint256) {
uint256 _keptSets = _setsToBuy.subS(_swapHowMuch, "AugurCP: When adding liquidity, tried to swap away more sets than you bought");
uint256 _gainedShares = rateSwap(_swapHowMuch, !_swapForYes);
uint256 _yesses; uint256 _nos;
if (_swapForYes) {
uint256 _yesses = _keptSets.add(_gainedShares);
uint256 _nos = _keptSets;
} else {
uint256 _yesses = _keptSets;
uint256 _nos = _keptSets.add(_gainedShares);
}
return rateAddLiquidity(_yesses, _nos);
}
// Removes shares from the liquidity pool.
// If _minSetsSold > 0 then also sell complete sets through burning and through swapping in the pool.
function removeLiquidity(uint256 _poolTokensToSell, uint256 _minSetsSold) external {
(uint256 _invalidShare, uint256 _noShare, uint256 _yesShare, uint256 _cashShare, uint256 _setsSold) = rateRemoveLiquidity(_poolTokensToSell, _minSetsSold);
require(_setsSold == 0 || _setsSold >= _minSetsSold, "AugurCP: Would not receive the minimum number of sets");
_burn(msg.sender, _poolTokensToSell);
shareTransfer(address(this), msg.sender, _invalidShare, _noShare, _yesShare);
shareToken.publicSellCompleteSets(augurMarket, _setsSold);
cash.transfer(msg.sender, _cashShare);
// CONSIDER: convert min(poolInvalid, poolYes, poolNo) to DAI by selling complete sets. Selling complete sets incurs Augur fees, maybe we should let the user sell the sets themselves if they want to pay the fee?
}
// Tells you how many shares you receive, how much cash you receive, and how many complete sets you burn for cash.
function rateRemoveLiquidity(uint256 _poolTokensToSell, uint256 _minSetsSold) public view returns (uint256 _invalidShare, uint256 _noShare, uint256 _yesShare, uint256 _cashShare, uint256 _setsSold) {
uint256 _poolSupply = totalSupply;
(uint256 _poolInvalid, uint256 _poolNo, uint256 _poolYes) = shareBalances(address(this));
uint256 _poolCash = cash.balanceOf(address(this));
_invalidShare = _poolInvalid.mul(_poolTokensToSell).div(_poolSupply);
_noShare = _poolNo.mul(_poolTokensToSell).div(_poolSupply);
_yesShare = _poolYes.mul(_poolTokensToSell).div(_poolSupply);
_cashShare = _poolCash.mul(_poolTokensToSell).div(_poolSupply);
_setsSold = 0;
if (_minSetsSold > 0) {
// First, how many complete sets you have
_setsSold = SafeMathUint256.min(_invalidShare, SafeMathUint256.min(_noShare, _yesShare));
_invalidShare -= _setsSold;
_noShare -= _setsSold;
_yesShare -= _setsSold;
_cashShare += _setsSold.mul(numTicks);
// Then, how many you can make from the pool
(uint256 _cashFromExit, uint256 _invalidFromUser, int256 _noFromUser, int256 _yesFromUser) = rateExitPosition(_invalidShare, _noShare, _yesShare);
_cashShare += _cashFromExit; // extra cash from selling sets to the pool
_invalidShare -= _invalidFromUser; // minus the invalids spent selling sets to the pool
if (_noFromUser > 0) {
_noShare -= uint256(_noFromUser);
} else { // user gained some No shares when making complete sets
_noShare += uint256(-_noFromUser);
}
if (_yesFromUser > 0) {
_yesShare -= uint256(_yesFromUser);
} else { // user gained some No shares when making complete sets
_yesShare += uint256(-_yesFromUser);
}
}
}
function enterPosition(uint256 _cashCost, bool _buyYes, uint256 _minShares) public returns (uint256) {
uint256 _sharesToBuy = rateEnterPosition(_cashCost, _buyYes);
require(_sharesToBuy >= _minShares, "AugurCP: Too few shares would be received for given cash.");
cash.transferFrom(msg.sender, address(this), _cashCost);
uint256 _setsToBuy = _cashCost.div(numTicks);
if (_buyYes) {
shareTransfer(address(this), msg.sender, _setsToBuy, 0, _sharesToBuy);
} else {
shareTransfer(address(this), msg.sender, _setsToBuy, _sharesToBuy, 0);
}
return _sharesToBuy;
}
// Tells you how many shares you get for given cash.
function rateEnterPosition(uint256 _cashToSpend, bool _buyYes) public view returns (uint256) {
uint256 _setsToBuy = _cashToSpend.div(numTicks);
(uint256 _poolInvalid, uint256 _poolNo, uint256 _poolYes) = shareBalances(address(this));
_poolInvalid = _poolInvalid.subS(_setsToBuy, "AugurCP: The pool doesn't have enough INVALID tokens to fulfill the request.");
_poolNo = _poolNo.subS(_setsToBuy, "AugurCP: The pool doesn't have enough NO tokens to fulfill the request.");
_poolYes = _poolYes.subS(_setsToBuy, "AugurCP: The pool doesn't have enough YES tokens to fulfill the request.");
// simulate user swapping YES to NO or NO to YES
uint256 _poolConstant = poolConstant(_poolYes, _poolNo);
if (_buyYes) {
// yesToUser + poolYes - poolConstant / (poolNo + _setsToBuy)
return _setsToBuy.add(_poolYes.sub(_poolConstant.div(_poolNo.add(_setsToBuy))));
} else {
return _setsToBuy.add(_poolNo.sub(_poolConstant.div(_poolYes.add(_setsToBuy))));
}
}
// Exits as much of the position as possible.
function exitAll(uint256 _minCashPayout) external {
(uint256 _userInvalid, uint256 _userNo, uint256 _userYes) = shareBalances(msg.sender);
exitPosition(_userInvalid, _userNo, _userYes, _minCashPayout);
}
// Sell as many of the given shares as possible, swapping yes<->no as-needed.
function exitPosition(uint256 _invalidShares, uint256 _noShares, uint256 _yesShares, uint256 _minCashPayout) public {
(uint256 _cashPayout, uint256 _invalidFromUser, int256 _noFromUser, int256 _yesFromUser) = rateExitPosition(_invalidShares, _noShares, _yesShares);
require(_cashPayout >= _minCashPayout, "Proceeds were less than the required payout");
if (_noFromUser < 0) {
shareToken.unsafeTransferFrom(address(this), msg.sender, NO, uint256(-_noFromUser));
_noFromUser = 0;
} else if (_yesFromUser < 0) {
shareToken.unsafeTransferFrom(address(this), msg.sender, YES, uint256(-_yesFromUser));
_yesFromUser = 0;
}
shareTransfer(msg.sender, address(this), _invalidFromUser, uint256(_noFromUser), uint256(_yesFromUser));
cash.transfer(msg.sender, _cashPayout);
}
function rateExitAll() public view returns (uint256 _cashPayout, uint256 _invalidFromUser, int256 _noFromUser, int256 _yesFromUser) {
(uint256 _userInvalid, uint256 _userNo, uint256 _userYes) = shareBalances(msg.sender);
return rateExitPosition(_userInvalid, _userNo, _userYes);
}
function rateExitPosition(uint256 _invalidShares, uint256 _noShares, uint256 _yesShares) public view returns (uint256 _cashPayout, uint256 _invalidFromUser, int256 _noFromUser, int256 _yesFromUser) {
(uint256 _poolNo, uint256 _poolYes) = yesNoShareBalances(address(this));
_invalidFromUser = _invalidShares;
_yesFromUser = int256(_yesShares);
_noFromUser = int256(_noShares);
uint256 _setsToSell = _invalidShares;
// Figure out how many shares we're buying in our synthetic swap and use that to figure out the final balance of Yes/No (setsToSell)
if (_yesShares > _noShares) {
uint256 _delta = _yesShares.sub(_noShares);
uint256 _noSharesToBuy = quadratic(1, -int256(_delta.add(_poolYes).add(_poolNo)), int256(_delta.mul(_poolNo)), _yesShares);
_setsToSell = _noShares.add(_noSharesToBuy);
} else if (_noShares > _yesShares) {
uint256 _delta = _noShares.sub(_yesShares);
uint256 _yesSharesToBuy = quadratic(1, -int256(_delta.add(_poolYes).add(_poolNo)), int256(_delta.mul(_poolYes)), _noShares);
_setsToSell = _yesShares.add(_yesSharesToBuy);
}
if (_invalidShares > _setsToSell) {
// We have excess Invalid shares that the user will just keep.
_invalidFromUser = _setsToSell;
} else {
// We don't have enough Invalid to actually close out the Yes/No shares. They will be kept by the user.
// Need to actually receive yes or no shares here since we are swapping to get partial complete sets but dont have enough yes/no to make full complete sets
if (_yesShares > _noShares) {
uint256 _noSharesToBuy = _setsToSell.sub(_noShares);
_noFromUser = _noFromUser.sub(int256(_noSharesToBuy));
_yesFromUser = int256(_yesShares.sub(_noShares).sub(_noSharesToBuy).sub(_invalidShares));
} else {
uint256 _yesSharesToBuy = _setsToSell.sub(_yesShares);
_yesFromUser = _yesFromUser.sub(int256(_yesSharesToBuy));
_noFromUser = int256(_noShares.sub(_yesShares.add(_yesSharesToBuy).sub(_invalidShares)));
}
_setsToSell = _invalidFromUser;
}
_cashPayout = _setsToSell.mul(numTicks);
}
function swap(uint256 _inputShares, bool _inputYes, uint256 _minOutputShares) external returns (uint256) {
uint _outputShares = rateSwap(_inputShares, _inputYes);
require(_outputShares >= _minOutputShares, "AugurCP: Swap would yield too few output shares.");
if (_inputYes) { // lose yesses, gain nos
shareToken.unsafeTransferFrom(msg.sender, address(this), YES, _inputShares);
shareToken.unsafeTransferFrom(address(this), msg.sender, NO, _outputShares);
} else { // gain yesses, lose nos
shareToken.unsafeTransferFrom(address(this), msg.sender, YES, _outputShares);
shareToken.unsafeTransferFrom(msg.sender, address(this), NO, _inputShares);
}
return _outputShares;
}
// How many of the other shares you would get for your shares.
function rateSwap(uint256 _inputShares, bool _inputYes) public view returns (uint256) {
(uint256 _poolNo, uint256 _poolYes) = yesNoShareBalances(address(this));
uint256 _poolConstant = poolConstant(_poolYes, _poolNo);
if (_inputYes) {
return _poolNo.sub(_poolConstant.div(_poolYes.add(_inputShares)));
} else {
return _poolYes.sub(_poolConstant.div(_poolNo.add(_inputShares)));
}
}
// When swapping (which includes entering and exiting positions), a fee is taken.
// The fee is a portion of the shares being swapped.
// Remove liquidity to collect fees.
function poolConstant(uint256 _poolYes, uint256 _poolNo) public view returns (uint256) {
uint256 beforeFee = _poolYes.mul(_poolNo);
if (beforeFee == 0) {
return 0;
} else {
return beforeFee.mul(1000).div(1000 - fee);
}
}
function shareBalances(address _owner) private view returns (uint256 _invalid, uint256 _no, uint256 _yes) {
uint256[] memory _tokenIds = new uint256[](3);
_tokenIds[0] = INVALID;
_tokenIds[1] = NO;
_tokenIds[2] = YES;
address[] memory _owners = new address[](3);
_owners[0] = _owner;
_owners[1] = _owner;
_owners[2] = _owner;
uint256[] memory _balances = shareToken.balanceOfBatch(_owners, _tokenIds);
_invalid = _balances[0];
_no = _balances[1];
_yes = _balances[2];
return (_invalid, _no, _yes);
}
function yesNoShareBalances(address _owner) private view returns (uint256 _no, uint256 _yes) {
uint256[] memory _tokenIds = new uint256[](2);
_tokenIds[0] = NO;
_tokenIds[1] = YES;
address[] memory _owners = new address[](2);
_owners[0] = _owner;
_owners[1] = _owner;
uint256[] memory _balances = shareToken.balanceOfBatch(_owners, _tokenIds);
_no = _balances[0];
_yes = _balances[1];
return (_no, _yes);
}
function shareTransfer(address _from, address _to, uint256 _invalidAmount, uint256 _noAmount, uint256 _yesAmount) private {
uint256 _size = (_invalidAmount != 0 ? 1 : 0) + (_noAmount != 0 ? 1 : 0) + (_yesAmount != 0 ? 1 : 0);
uint256[] memory _tokenIds = new uint256[](_size);
uint256[] memory _amounts = new uint256[](_size);
if (_size == 0) {
return;
} else if (_size == 1) {
_tokenIds[0] = _invalidAmount != 0 ? INVALID : _noAmount != 0 ? NO : YES;
_amounts[0] = _invalidAmount != 0 ? _invalidAmount : _noAmount != 0 ? _noAmount : _yesAmount;
} else if (_size == 2) {
_tokenIds[0] = _invalidAmount != 0 ? INVALID : NO;
_tokenIds[1] = _invalidAmount != 0 ? YES : NO;
_amounts[0] = _invalidAmount != 0 ? _invalidAmount : _noAmount;
_amounts[1] = _invalidAmount != 0 ? _yesAmount : _noAmount;
} else {
_tokenIds[0] = INVALID;
_tokenIds[1] = NO;
_tokenIds[2] = YES;
_amounts[0] = _invalidAmount;
_amounts[1] = _noAmount;
_amounts[2] = _yesAmount;
}
shareToken.unsafeBatchTransferFrom(_from, _to, _tokenIds, _amounts);
}
function quadratic(int256 _a, int256 _b, int256 _c, uint256 _maximum) internal pure returns (uint256) {
int256 _piece = SafeMathInt256.sqrt(_b*_b - (_a.mul(_c).mul(4)));
int256 _resultPlus = (-_b + _piece) / (2 * _a);
int256 _resultMinus = (-_b - _piece) / (2 * _a);
// Choose correct answer based on maximum.
if (_resultMinus < 0) _resultMinus = -_resultMinus;
if (_resultPlus < 0) _resultPlus = -_resultPlus;
if (_resultPlus > int256(_maximum)) {
return uint256(_resultMinus);
} else {
return uint256(_resultPlus);
}
}
function onTokenTransfer(address _from, address _to, uint256 _value) internal {}
}
contract IFeePot is IERC20 {
function depositFees(uint256 _amount) external returns (bool);
function withdrawableFeesOf(address _owner) external view returns(uint256);
function redeem() external returns (bool);
function cash() external view returns (ICash);
}
interface IParaShareToken {
function cash() external view returns (ICash);
function augur() external view returns (address);
function approveUniverse(IParaUniverse _paraUniverse) external;
function buyCompleteSets(IMarket _market, address _account, uint256 _amount) external returns (bool);
function publicSellCompleteSets(IMarket _market, uint256 _amount) external returns (uint256 _creatorFee, uint256 _reportingFee);
function publicBuyCompleteSets(IMarket _market, uint256 _amount) external returns (bool);
function getTokenId(IMarket _market, uint256 _outcome) external pure returns (uint256 _tokenId);
function unsafeTransferFrom(address _from, address _to, uint256 _id, uint256 _value) external;
function balanceOf(address owner, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances_);
function unsafeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values) external;
}
interface IParaUniverse {
function getFeePot() external view returns (IFeePot);
function getReputationToken() external view returns (IV2ReputationToken);
function originUniverse() external view returns (IUniverse);
function setMarketFinalized(IMarket _market, uint256 _totalSupply) external returns (bool);
function withdraw(address _recipient, uint256 _amount, address _market) external returns (bool);
function deposit(address _sender, uint256 _amount, address _market) external returns (bool);
function decrementOpenInterest(uint256 _amount) external returns (bool);
function incrementOpenInterest(uint256 _amount) external returns (bool);
function recordMarketCreatorFees(IMarket _market, uint256 _marketCreatorFees, address _sourceAccount) external returns (bool);
function getMarketOpenInterest(IMarket _market) external view returns (uint256);
function getOrCacheReportingFeeDivisor() external returns (uint256);
function getReportingFeeDivisor() external view returns (uint256);
function setOrigin(IUniverse _originUniverse) external;
}
contract IAffiliateValidator {
function validateReference(address _account, address _referrer) external view returns (bool);
}
contract IDisputeWindow is ITyped, IERC20 {
function invalidMarketsTotal() external view returns (uint256);
function validityBondTotal() external view returns (uint256);
function incorrectDesignatedReportTotal() external view returns (uint256);
function initialReportBondTotal() external view returns (uint256);
function designatedReportNoShowsTotal() external view returns (uint256);
function designatedReporterNoShowBondTotal() external view returns (uint256);
function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public;
function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getReputationToken() public view returns (IReputationToken);
function getStartTime() public view returns (uint256);
function getEndTime() public view returns (uint256);
function getWindowId() public view returns (uint256);
function isActive() public view returns (bool);
function isOver() public view returns (bool);
function onMarketFinalized() public;
function redeem(address _account) public returns (bool);
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public;
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32);
function doInitialReport(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getDisputeWindow() public view returns (IDisputeWindow);
function getNumberOfOutcomes() public view returns (uint256);
function getNumTicks() public view returns (uint256);
function getMarketCreatorSettlementFeeDivisor() public view returns (uint256);
function getForkingMarket() public view returns (IMarket _market);
function getEndTime() public view returns (uint256);
function getWinningPayoutDistributionHash() public view returns (bytes32);
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningReportingParticipant() public view returns (IReportingParticipant);
function getReputationToken() public view returns (IV2ReputationToken);
function getFinalizationTime() public view returns (uint256);
function getInitialReporter() public view returns (IInitialReporter);
function getDesignatedReportingEndTime() public view returns (uint256);
function getValidityBondAttoCash() public view returns (uint256);
function affiliateFeeDivisor() external view returns (uint256);
function getNumParticipants() public view returns (uint256);
function getDisputePacingOn() public view returns (bool);
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256);
function recordMarketCreatorFees(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function isFinalizedAsInvalid() public view returns (bool);
function finalize() public returns (bool);
function isFinalized() public view returns (bool);
function getOpenInterest() public view returns (uint256);
}
contract IReportingParticipant {
function getStake() public view returns (uint256);
function getPayoutDistributionHash() public view returns (bytes32);
function liquidateLosing() public;
function redeem(address _redeemer) public returns (bool);
function isDisavowed() public view returns (bool);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getMarket() public view returns (IMarket);
function getSize() public view returns (uint256);
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public;
function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public;
function designatedReporterShowed() public view returns (bool);
function initialReporterWasCorrect() public view returns (bool);
function getDesignatedReporter() public view returns (address);
function getReportTimestamp() public view returns (uint256);
function migrateToNewUniverse(address _designatedReporter) public;
function returnRepFromDisavow() public;
}
contract IReputationToken is IERC20 {
function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool);
function migrateIn(address _reporter, uint256 _attotokens) public returns (bool);
function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getTotalMigrated() public view returns (uint256);
function getTotalTheoreticalSupply() public view returns (uint256);
function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool);
}
contract IShareToken is ITyped, IERC1155 {
function initialize(IAugur _augur) external;
function initializeMarket(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public;
function unsafeTransferFrom(address _from, address _to, uint256 _id, uint256 _value) public;
function unsafeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public;
function claimTradingProceeds(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees);
function getMarket(uint256 _tokenId) external view returns (IMarket);
function getOutcome(uint256 _tokenId) external view returns (uint256);
function getTokenId(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId);
function getTokenIds(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds);
function buyCompleteSets(IMarket _market, address _account, uint256 _amount) external returns (bool);
function buyCompleteSetsForTrade(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool);
function sellCompleteSets(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function sellCompleteSetsForTrade(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function totalSupplyForMarketOutcome(IMarket _market, uint256 _outcome) public view returns (uint256);
function balanceOfMarketOutcome(IMarket _market, uint256 _outcome, address _account) public view returns (uint256);
function lowestBalanceOfMarketOutcomes(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256);
}
contract IUniverse {
function creationTime() external view returns (uint256);
function marketBalance(address) external view returns (uint256);
function fork() public returns (bool);
function updateForkValues() public returns (bool);
function getParentUniverse() public view returns (IUniverse);
function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse);
function getReputationToken() public view returns (IV2ReputationToken);
function getForkingMarket() public view returns (IMarket);
function getForkEndTime() public view returns (uint256);
function getForkReputationGoal() public view returns (uint256);
function getParentPayoutDistributionHash() public view returns (bytes32);
function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256);
function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow);
function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOpenInterestInAttoCash() public view returns (uint256);
function getTargetRepMarketCapInAttoCash() public view returns (uint256);
function getOrCacheValidityBond() public returns (uint256);
function getOrCacheDesignatedReportStake() public returns (uint256);
function getOrCacheDesignatedReportNoShowBond() public returns (uint256);
function getOrCacheMarketRepBond() public returns (uint256);
function getOrCacheReportingFeeDivisor() public returns (uint256);
function getDisputeThresholdForFork() public view returns (uint256);
function getDisputeThresholdForDisputePacing() public view returns (uint256);
function getInitialReportMinValue() public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getReportingFeeDivisor() public view returns (uint256);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256);
function isOpenInterestCash(address) public view returns (bool);
function isForkingMarket() public view returns (bool);
function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow);
function getDisputeWindowStartTimeAndDuration(uint256 _timestamp, bool _initial) public view returns (uint256, uint256);
function isParentOf(IUniverse _shadyChild) public view returns (bool);
function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool);
function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool);
function isContainerForMarket(IMarket _shadyTarget) public view returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool);
function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool);
function decrementOpenInterest(uint256 _amount) public returns (bool);
function decrementOpenInterestFromMarket(IMarket _market) public returns (bool);
function incrementOpenInterest(uint256 _amount) public returns (bool);
function getWinningChildUniverse() public view returns (IUniverse);
function isForking() public view returns (bool);
function deposit(address _sender, uint256 _amount, address _market) public returns (bool);
function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool);
function pokeRepMarketCapInAttoCash() public returns (uint256);
function createScalarMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket);
function createYesNoMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, string memory _extraInfo) public returns (IMarket _newMarket);
function createCategoricalMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, bytes32[] memory _outcomes, string memory _extraInfo) public returns (IMarket _newMarket);
function runPeriodicals() external returns (bool);
}
contract IV2ReputationToken is IReputationToken {
function parentUniverse() external returns (IUniverse);
function burnForMarket(uint256 _amountToBurn) public returns (bool);
function mintForWarpSync(uint256 _amountToMint, address _target) public returns (bool);
function getLegacyRepToken() public view returns (IERC20);
function symbol() public view returns (string memory);
}
contract IAugurTrading {
function lookup(bytes32 _key) public view returns (address);
function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool);
function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool);
function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool);
function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool);
function logZeroXOrderCanceled(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public;
}
contract IOrders {
function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId);
function removeOrder(bytes32 _orderId) external returns (bool);
function getMarket(bytes32 _orderId) public view returns (IMarket);
function getOrderType(bytes32 _orderId) public view returns (Order.Types);
function getOutcome(bytes32 _orderId) public view returns (uint256);
function getAmount(bytes32 _orderId) public view returns (uint256);
function getPrice(bytes32 _orderId) public view returns (uint256);
function getOrderCreator(bytes32 _orderId) public view returns (address);
function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderDataForCancel(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address);
function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data);
function getBetterOrderId(bytes32 _orderId) public view returns (bytes32);
function getWorseOrderId(bytes32 _orderId) public view returns (bytes32);
function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256);
function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32);
function getTotalEscrowed(IMarket _market) public view returns (uint256);
function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool);
function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool);
function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool);
function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool);
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function create(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) {
require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.lookup("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.lookup("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = calculateOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function calculateOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) {
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) {
getOrderId(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.saveOrder(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment