Verified contractExactMIT
CloneHelper
Address0x55cd2820735db56ca0965be224d71994265f8bee
- Balance
0 ETH
- Transactions
26
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,769,590
- Creation transaction
- 0xea8e1416ef…bb7d83eaa2
14 files
- contracts/minting/v2/CloneHelper.solmain2.52 KB
- contracts/equity/IGovernance.sol321 B
- contracts/erc20/IERC20.sol2.96 KB
- contracts/minting/IPosition.sol1.8 KB
- contracts/minting/IPositionFactory.sol545 B
- contracts/minting/PositionRoller.sol7.44 KB
- contracts/minting/v1/IFrankencoin.sol1.84 KB
- contracts/minting/v1/IReserve.sol294 B
- contracts/minting/v2/IPositionV2.sol2.61 KB
- contracts/minting/v2/MintingHubV2.sol19.1 KB
- contracts/rate/ILeadrate.sol201 B
- contracts/stablecoin/IBasicFrankencoin.sol1.15 KB
- contracts/stablecoin/IFrankencoin.sol966 B
- contracts/utils/Ownable.sol1.54 KB
contracts/minting/v2/CloneHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./MintingHubV2.sol";
import "./IPositionV2.sol";
import "../../erc20/IERC20.sol";
import "../../utils/Ownable.sol";
/**
* @title CloneHelper
* @notice Helper contract that allows cloning a position and immediately setting a different liquidation price.
*
* The clone always mints at the parent's price first, then adjusts if needed:
* - Same price as parent: no adjustment, no cooldown.
* - Lower price: adjusted downward immediately (no cooldown).
* - Higher price: adjusted upward (3-day cooldown triggered, but the initial mint already happened).
*/
contract CloneHelper {
MintingHubV2 public immutable HUB;
constructor(address hub_) {
HUB = MintingHubV2(hub_);
}
/**
* @notice Clone a position, mint, and optionally set a new liquidation price in one transaction.
* @dev The caller must have approved this contract for the collateral token.
* Minting always happens at the parent's price. The price is only adjusted afterwards
* if newPrice differs from the parent's price.
* @param parent address of the position to clone
* @param initialCollateral amount of collateral to deposit
* @param initialMint amount of ZCHF to mint
* @param expiration expiration timestamp for the clone
* @param newPrice the desired liquidation price for the clone
* @return pos address of the newly created position
*/
function cloneWithPrice(address parent, uint256 initialCollateral, uint256 initialMint, uint40 expiration, uint256 newPrice) external returns (address) {
IERC20 collateral = IPositionV2(parent).collateral();
collateral.transferFrom(msg.sender, address(this), initialCollateral);
collateral.approve(address(HUB), initialCollateral);
// Clone and mint at the parent's price
address pos = HUB.clone(address(this), parent, initialCollateral, initialMint, expiration);
// Only adjust if the desired price differs from what was inherited
if (newPrice != IPositionV2(parent).price()) {
IPositionV2(pos).adjustPrice(newPrice);
}
// Forward any minted ZCHF to the caller
IERC20 zchf = IERC20(address(HUB.zchf()));
zchf.transfer(msg.sender, zchf.balanceOf(address(this)));
// Transfer ownership to the caller
Ownable(pos).transferOwnership(msg.sender);
return pos;
}
}
contracts/equity/IGovernance.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGovernance {
function checkQualified(address sender, address[] calldata helpers) external view;
}
struct SyncVote {
address voter;
uint256 votes;
address delegatee;
}
struct SyncMessage {
SyncVote[] votes;
uint256 totalVotes;
}
contracts/erc20/IERC20.sol
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016-2019 zOS Global Limited
*
*/
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns always true. Throws error on failure.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value can change when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns always true. Throws error on failure.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contracts/minting/IPosition.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../erc20/IERC20.sol";
import "../stablecoin/IFrankencoin.sol";
interface IPosition {
function initialize(address parent, uint40 _expiration) external;
function hub() external view returns(address);
function original() external view returns (address);
function collateral() external view returns (IERC20);
function minimumCollateral() external view returns (uint256);
function challengePeriod() external view returns (uint40);
function expiration() external view returns (uint40);
function price() external view returns (uint256);
function deny(address[] calldata helpers, string calldata message) external;
function mint(address target, uint256 amount) external;
function repay(uint256 amount) external returns (uint256);
function adjust(uint256 newMinted, uint256 newCollateral, uint256 newPrice) external;
function minted() external view returns (uint256);
function availableForMinting() external view returns (uint256);
function reserveContribution() external view returns (uint24);
function withdrawCollateral(address target, uint256 amount) external;
function getUsableMint(uint256 totalMint, bool beforeFees) external view returns (uint256);
function getMintAmount(uint256 usableMint) external view returns (uint256);
function challengeData() external view returns (uint256 liqPrice, uint40 phase);
function notifyChallengeStarted(uint256 size) external;
function notifyChallengeAverted(uint256 size) external;
function notifyChallengeSucceeded(address _bidder, uint256 _size) external returns (address, uint256, uint256, uint32);
function forceSale(address buyer, uint256 collAmount, uint256 proceeds) external;
}contracts/minting/IPositionFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPositionFactory {
function createNewPosition(
address _owner,
address _zchf,
address _collateral,
uint256 _minCollateral,
uint256 _initialLimit,
uint40 _initPeriodSeconds,
uint40 _duration,
uint40 _challengePeriod,
uint24 _riskPremiumPPM,
uint256 _liqPrice,
uint24 _reserve
) external returns (address);
function clonePosition(address _existing) external returns (address);
}
contracts/minting/PositionRoller.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../erc20/IERC20.sol";
import "../stablecoin/IFrankencoin.sol";
import "./IPosition.sol";
import "../utils/Ownable.sol";
/**
* @title PositionRoller
*
* Helper to roll over a debt from an old position to a new one.
* Both positions should have the same collateral. Otherwise, it does not make much sense.
*/
contract PositionRoller {
IFrankencoin private zchf;
error NotOwner(address pos);
error NotPosition(address pos);
error Log(uint256, uint256, uint256);
event Roll(address source, uint256 collWithdraw, uint256 repay, address target, uint256 collDeposit, uint256 mint);
constructor(address zchf_) {
zchf = IFrankencoin(zchf_);
}
/**
* Convenience method to roll and old position into a new one.
*
* Pre-condition is an allowance for the roller to spend the collateral assset on behalf of the caller,
* i.e. one should set collateral.approve(roller, collateral.balanceOf(sourcePosition));
*
* The following is assumed:
* - If the limit of the target position permits, the user wants to roll everything
* - The user does not want to add additional collateral, but excess collateral is returned
* - If not enough can be minted in the new position, it is ok for the roller to use ZCHF from the msg.sender
*/
function rollFully(IPosition source, IPosition target) external {
rollFullyWithExpiration(source, target, target.expiration());
}
/**
* Like rollFully, but with a custom expiration date for the new position.
*/
function rollFullyWithExpiration(IPosition source, IPosition target, uint40 expiration) public {
require(source.collateral() == target.collateral());
uint256 repay = findRepaymentAmount(source);
uint256 mintAmount = target.getMintAmount(repay);
uint256 collateralToWithdraw = IERC20(source.collateral()).balanceOf(address(source));
uint256 targetPrice = target.price();
uint256 depositAmount = (mintAmount * 10**18 + targetPrice - 1) / targetPrice; // round up
if (depositAmount > collateralToWithdraw){
// If we need more collateral than available from the old position, we opt for taking
// the missing funds from the caller instead of taking additional collateral from the caller
depositAmount = collateralToWithdraw;
mintAmount = depositAmount * target.price() / 10**18; // round down, rest will be taken from caller
}
roll(source, repay, collateralToWithdraw, target, mintAmount, depositAmount, expiration);
}
/**
* Doing a binary search is not very efficient, but guaranteed to return a valid result without rounding errors.
* To save gas costs, the frontend can also call this and other methods to calculate the right parameters and
* then call 'roll' directly.
*/
function findRepaymentAmount(IPosition pos) public view returns (uint256) {
uint256 minted = pos.minted();
uint24 reservePPM = pos.reserveContribution();
if (minted == 0){
return 0;
}
uint256 higherResult = zchf.calculateFreedAmount(minted, reservePPM);
if (higherResult == minted){
return minted;
}
return binarySearch(minted, reservePPM, 0, 0, minted, higherResult);
}
// max call stack depth is 1024 in solidity. Binary search on 256 bit number takes at most 256 steps, so it should be fine.
function binarySearch(uint256 target, uint24 reservePPM, uint256 lowerBound, uint256 lowerResult, uint256 higherBound, uint256 higherResult) internal view returns (uint256) {
uint256 middle = (lowerBound + higherBound) / 2;
if (middle == lowerBound){
return higherBound; // we have reached max precision without exact match, return next higher result to be on the safe side
} else {
uint256 middleResult = zchf.calculateFreedAmount(middle, reservePPM);
if (middleResult == target){
return middle;
} else if (middleResult < target){
return binarySearch(target, reservePPM, middle, middleResult, higherBound, higherResult);
} else {
return binarySearch(target, reservePPM, lowerBound, lowerResult, middle, middleResult);
}
}
}
/**
* Rolls the source position into the target position using a flash loan.
* Both the source and the target position must recognize this roller.
* It is the responsibility of the caller to ensure that both positions are valid contracts.
*
* @param source The source position, must be owned by the msg.sender .
* @param repay The amount to flash loan in order to repay the source position and free up some or all collateral.
* @param collWithdraw Collateral to move from the source position to the msg.sender .
* @param target The target position. If not owned by msg.sender or if it does not have the desired expiration,
* it is cloned to create a position owned by the msg.sender.
* @param mint The amount to be minted from the target position using collateral from msg.sender.
* @param collDeposit The amount of collateral to be send from msg.sender to the target position.
* @param expiration The desired expiration date for the target position.
*/
function roll(IPosition source, uint256 repay, uint256 collWithdraw, IPosition target, uint256 mint, uint256 collDeposit, uint40 expiration) public valid(source) valid(target) own(source) {
zchf.mint(address(this), repay); // take a flash loan
source.repay(repay);
source.withdrawCollateral(msg.sender, collWithdraw);
if (mint > 0){
IERC20 targetCollateral = IERC20(target.collateral());
if (Ownable(address(target)).owner() != msg.sender || expiration != target.expiration()){
targetCollateral.transferFrom(msg.sender, address(this), collDeposit); // get the new collateral
targetCollateral.approve(target.hub(), collDeposit); // approve the new collateral and clone:
target = IPosition(IMintingHub(target.hub()).clone(msg.sender, address(target), collDeposit, mint, expiration));
} else {
// We can roll into the provided existing position
// We do not verify whether the target position has been created by the known minting hub in order
// to allow positions to be rolled into future versions of the minting hub
targetCollateral.transferFrom(msg.sender, address(target), collDeposit);
target.mint(msg.sender, mint);
}
}
zchf.burnFrom(msg.sender, repay); // repay the flash loan
emit Roll(address(source), collWithdraw, repay, address(target), collDeposit, mint);
}
modifier own(IPosition pos) {
if (Ownable(address(pos)).owner() != msg.sender) revert NotOwner(address(pos));
_;
}
modifier valid(IPosition pos) {
if (zchf.getPositionParent(address(pos)) == address(0x0)) revert NotPosition(address(pos));
_;
}
}
interface IMintingHub {
function clone(address owner, address parent, uint256 _initialCollateral, uint256 _initialMint, uint40 expiration) external returns (address);
}
contracts/minting/v1/IFrankencoin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../erc20/IERC20.sol";
import "./IReserve.sol";
interface IFrankencoin is IERC20 {
function MIN_FEE() external view returns (uint256);
function MIN_APPLICATION_PERIOD() external view returns (uint256);
function suggestMinter(address _minter, uint256 _applicationPeriod, uint256 _applicationFee, string calldata _message) external;
function registerPosition(address position) external;
function denyMinter(address minter, address[] calldata helpers, string calldata message) external;
function reserve() external view returns (IReserve);
function minterReserve() external view returns (uint256);
function calculateAssignedReserve(uint256 mintedAmount, uint32 _reservePPM) external view returns (uint256);
function calculateFreedAmount(uint256 amountExcludingReserve, uint32 reservePPM) external view returns (uint256);
function equity() external view returns (uint256);
function isMinter(address minter) external view returns (bool);
function getPositionParent(address position) external view returns (address);
function mint(address target, uint256 amount) external;
function mintWithReserve(address target, uint256 amount, uint32 reservePPM, uint32 feePPM) external;
function burnFrom(address target, uint256 amount) external;
function burnWithoutReserve(uint256 amountIncludingReserve, uint32 reservePPM) external;
function burnFromWithReserve(address payer, uint256 targetTotalBurnAmount, uint32 _reservePPM) external returns (uint256);
function burnWithReserve(uint256 amountExcludingReserve, uint32 reservePPM) external returns (uint256);
function coverLoss(address source, uint256 amount) external;
function collectProfits(address source, uint256 _amount) external;
}
contracts/minting/v1/IReserve.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../erc20/IERC20.sol";
interface IReserve is IERC20 {
function invest(uint256 amount, uint256 expected) external returns (uint256);
function checkQualified(address sender, address[] calldata helpers) external view;
}
contracts/minting/v2/IPositionV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../erc20/IERC20.sol";
interface IPositionV2 {
function hub() external view returns (address);
function collateral() external view returns (IERC20);
function minimumCollateral() external view returns (uint256);
function price() external view returns (uint256);
function minted() external view returns (uint256);
function challengedAmount() external view returns (uint256);
function original() external view returns (address);
function expiration() external view returns (uint40);
function cooldown() external view returns (uint40);
function limit() external view returns (uint256);
function challengePeriod() external view returns (uint40);
function start() external view returns (uint40);
function riskPremiumPPM() external view returns (uint24);
function reserveContribution() external view returns (uint24);
function initialize(address parent, uint40 _expiration) external;
function assertCloneable() external;
function notifyMint(uint256 mint_) external;
function notifyRepaid(uint256 repaid_) external;
function availableForClones() external view returns (uint256);
function availableForMinting() external view returns (uint256);
function deny(address[] calldata helpers, string calldata message) external;
function getUsableMint(uint256 totalMint, bool afterFees) external view returns (uint256);
function getMintAmount(uint256 usableMint) external view returns (uint256);
function adjust(uint256 newMinted, uint256 newCollateral, uint256 newPrice) external;
function adjustPrice(uint256 newPrice) external;
function mint(address target, uint256 amount) external;
function calculateCurrentFee() external view returns (uint24);
function annualInterestPPM() external view returns (uint24);
function calculateFee(uint256 exp) external view returns (uint24);
function repay(uint256 amount) external returns (uint256);
function forceSale(address buyer, uint256 collAmount, uint256 proceeds) external;
function withdraw(address token, address target, uint256 amount) external;
function withdrawCollateral(address target, uint256 amount) external;
function challengeData() external view returns (uint256 liqPrice, uint40 phase);
function notifyChallengeStarted(uint256 size) external;
function notifyChallengeAverted(uint256 size) external;
function notifyChallengeSucceeded(address _bidder, uint256 _size) external returns (address, uint256, uint256, uint32);
}
contracts/minting/v2/MintingHubV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/Ownable.sol";
import "../../erc20/IERC20.sol";
import "../v1/IReserve.sol";
import "../../rate/ILeadrate.sol";
import "../v1/IFrankencoin.sol";
import "./IPositionV2.sol";
import "../IPositionFactory.sol";
import {PositionRoller} from "../PositionRoller.sol";
/**
* @title Minting Hub
* @notice The central hub for creating, cloning and challenging collateralized Frankencoin positions.
* @dev Only one instance of this contract is required, whereas every new position comes with a new position
* contract. Pending challenges are stored as structs in an array.
*/
contract MintingHubV2 {
/**
* @notice Irrevocable fee in ZCHF when proposing a new position (but not when cloning an existing one).
*/
uint256 public constant OPENING_FEE = 1000 * 10 ** 18;
/**
* @notice The challenger reward in parts per million (ppm) relative to the challenged amount, whereas
* challenged amount if defined as the challenged collateral amount times the liquidation price.
*/
uint256 public constant CHALLENGER_REWARD = 20000; // 2%
uint256 public constant EXPIRED_PRICE_FACTOR = 10;
IPositionFactory private immutable POSITION_FACTORY; // position contract to clone
IFrankencoin public immutable zchf; // currency
PositionRoller public immutable roller; // helper to roll positions
ILeadrate public immutable rate; // to determine the interest rate
Challenge[] public challenges; // list of open challenges
/**
* @notice Map to remember pending postponed collateral returns.
* @dev It maps collateral => beneficiary => amount.
*/
mapping(address collateral => mapping(address owner => uint256 amount)) public pendingReturns;
struct Challenge {
address challenger; // the address from which the challenge was initiated
uint40 start; // the start of the challenge
IPositionV2 position; // the position that was challenged
uint256 size; // how much collateral the challenger provided
}
event PositionOpened(address indexed owner, address indexed position, address original, address collateral);
event ChallengeStarted(address indexed challenger, address indexed position, uint256 size, uint256 number);
event ChallengeAverted(address indexed position, uint256 number, uint256 size);
event ChallengeSucceeded(address indexed position, uint256 number, uint256 bid, uint256 acquiredCollateral, uint256 challengeSize);
event PostPonedReturn(address collateral, address indexed beneficiary, uint256 amount);
event ForcedSale(address pos, uint256 amount, uint256 priceE36MinusDecimals);
error UnexpectedPrice();
error InvalidPos();
error IncompatibleCollateral();
error InsufficientCollateral();
modifier validPos(address position) {
if (zchf.getPositionParent(position) != address(this)) revert InvalidPos();
_;
}
constructor(address _zchf, address _leadrate, address _roller, address _factory) {
zchf = IFrankencoin(_zchf);
rate = ILeadrate(_leadrate);
POSITION_FACTORY = IPositionFactory(_factory);
roller = PositionRoller(_roller);
}
/**
* @notice Open a collateralized loan position. See also https://docs.frankencoin.com/positions/open .
* @dev For a successful call, you must set an allowance for the collateral token, allowing
* the minting hub to transfer the initial collateral amount to the newly created position and to
* withdraw the fees.
*
* @param _collateralAddress address of collateral token
* @param _minCollateral minimum collateral required to prevent dust amounts
* @param _initialCollateral amount of initial collateral to be deposited
* @param _mintingMaximum maximal amount of ZCHF that can be minted by the position owner
* @param _expirationSeconds position tenor in unit of timestamp (seconds) from 'now'
* @param _challengeSeconds challenge period. Longer for less liquid collateral.
* @param _riskPremium ppm of minted amount that is added to the applicible minting fee as a risk premium
* @param _liqPrice Liquidation price with (36 - token decimals) decimals,
* e.g. 18 decimals for an 18 dec collateral, 36 decs for a 0 dec collateral.
* @param _reservePPM ppm of minted amount that is locked as borrower's reserve, e.g. 20%
* @return address address of created position
*/
function openPosition(
address _collateralAddress,
uint256 _minCollateral,
uint256 _initialCollateral,
uint256 _mintingMaximum,
uint40 _initPeriodSeconds,
uint40 _expirationSeconds,
uint40 _challengeSeconds,
uint24 _riskPremium,
uint256 _liqPrice,
uint24 _reservePPM
) public returns (address) {
{
require(_riskPremium <= 1000000);
require(CHALLENGER_REWARD <= _reservePPM && _reservePPM <= 1000000);
require(IERC20(_collateralAddress).decimals() <= 24); // leaves 12 digits for price
uint256 invalidAmount = IERC20(_collateralAddress).totalSupply() + 1;
try IERC20(_collateralAddress).transfer(address(0x123), invalidAmount) {
revert IncompatibleCollateral(); // we need a collateral that reverts on failed transfers
} catch Error(string memory /*reason*/) {} catch Panic(uint /*errorCode*/) {} catch (bytes memory /*lowLevelData*/) {}
if (_initialCollateral < _minCollateral) revert InsufficientCollateral();
if (_minCollateral * _liqPrice < 5000 ether * 10 ** 18) revert InsufficientCollateral(); // must start with at least 5000 ZCHF worth of collateral
}
IPositionV2 pos = IPositionV2(
POSITION_FACTORY.createNewPosition(msg.sender, address(zchf), _collateralAddress, _minCollateral, _mintingMaximum, _initPeriodSeconds, _expirationSeconds, _challengeSeconds, _riskPremium, _liqPrice, _reservePPM)
);
zchf.registerPosition(address(pos));
zchf.collectProfits(msg.sender, OPENING_FEE);
IERC20(_collateralAddress).transferFrom(msg.sender, address(pos), _initialCollateral);
emit PositionOpened(msg.sender, address(pos), address(pos), _collateralAddress);
return address(pos);
}
function clone(address parent, uint256 _initialCollateral, uint256 _initialMint, uint40 expiration) public returns (address) {
return clone(msg.sender, parent, _initialCollateral, _initialMint, expiration);
}
/**
* @notice Clones an existing position and immediately tries to mint the specified amount using the given collateral.
* @dev This needs an allowance to be set on the collateral contract such that the minting hub can get the collateral.
*/
function clone(address owner, address parent, uint256 _initialCollateral, uint256 _initialMint, uint40 expiration) public validPos(parent) returns (address) {
address pos = POSITION_FACTORY.clonePosition(parent);
IPositionV2 child = IPositionV2(pos);
child.initialize(parent, expiration);
zchf.registerPosition(pos);
IERC20 collateral = child.collateral();
if (_initialCollateral < child.minimumCollateral()) revert InsufficientCollateral();
collateral.transferFrom(msg.sender, pos, _initialCollateral); // collateral must still come from sender for security
emit PositionOpened(owner, address(pos), parent, address(collateral));
child.mint(owner, _initialMint);
Ownable(address(child)).transferOwnership(owner);
return address(pos);
}
/**
* @notice Launch a challenge (Dutch auction) on a position
* @param _positionAddr address of the position we want to challenge
* @param _collateralAmount amount of the collateral we want to challenge
* @param minimumPrice position.price() to guard against the minter fruntrunning with a price change
* @return index of the challenge in challenge-array
*/
function challenge(address _positionAddr, uint256 _collateralAmount, uint256 minimumPrice) external validPos(_positionAddr) returns (uint256) {
IPositionV2 position = IPositionV2(_positionAddr);
// challenger should be ok if frontrun by owner with a higher price
// in case owner fruntruns challenger with small price decrease to prevent challenge,
// the challenger should set minimumPrice to market price
if (position.price() < minimumPrice) revert UnexpectedPrice();
IERC20(position.collateral()).transferFrom(msg.sender, address(this), _collateralAmount);
uint256 pos = challenges.length;
challenges.push(Challenge(msg.sender, uint40(block.timestamp), position, _collateralAmount));
position.notifyChallengeStarted(_collateralAmount);
emit ChallengeStarted(msg.sender, address(position), _collateralAmount, pos);
return pos;
}
/**
* @notice Post a bid in ZCHF given an open challenge.
*
* @dev In case that the collateral cannot be transfered back to the challenger (i.e. because the collateral token
* has a blacklist and the challenger is on it), it is possible to postpone the return of the collateral.
*
* @param _challengeNumber index of the challenge as broadcast in the event
* @param size how much of the collateral the caller wants to bid for at most
* (automatically reduced to the available amount)
* @param postponeCollateralReturn To postpone the return of the collateral to the challenger. Usually false.
*/
function bid(uint32 _challengeNumber, uint256 size, bool postponeCollateralReturn) external {
Challenge memory _challenge = challenges[_challengeNumber];
(uint256 liqPrice, uint40 phase) = _challenge.position.challengeData();
size = _challenge.size < size ? _challenge.size : size; // cannot bid for more than the size of the challenge
if (block.timestamp <= _challenge.start + phase) {
_avertChallenge(_challenge, _challengeNumber, liqPrice, size);
emit ChallengeAverted(address(_challenge.position), _challengeNumber, size);
} else {
_returnChallengerCollateral(_challenge, _challengeNumber, size, postponeCollateralReturn);
(uint256 transferredCollateral, uint256 offer) = _finishChallenge(_challenge, liqPrice, phase, size);
emit ChallengeSucceeded(address(_challenge.position), _challengeNumber, offer, transferredCollateral, size);
}
}
function _finishChallenge(Challenge memory _challenge, uint256 liqPrice, uint40 phase, uint256 size) internal returns (uint256, uint256) {
// Repayments depend on what was actually minted, whereas bids depend on the available collateral
(address owner, uint256 collateral, uint256 repayment, uint32 reservePPM) = _challenge.position.notifyChallengeSucceeded(msg.sender, size);
// No overflow possible thanks to invariant (col * price <= limit * 10**18)
// enforced in Position.setPrice and knowing that collateral <= col.
uint256 offer = (_calculatePrice(_challenge.start + phase, phase, liqPrice) * collateral) / 10 ** 18;
zchf.transferFrom(msg.sender, address(this), offer); // get money from bidder
uint256 reward = (offer * CHALLENGER_REWARD) / 1000_000;
zchf.transfer(_challenge.challenger, reward); // pay out the challenger reward
uint256 fundsAvailable = offer - reward; // funds available after reward
// Example: available funds are 90, repayment is 50, reserve 20%. Then 20%*(90-50)=16 are collected as profits
// and the remaining 34 are sent to the position owner. If the position owner maxed out debt before the challenge
// started and the liquidation price was 100, they would be slightly better off as they would get away with 80
// instead of 40+36 = 76 in this example.
if (fundsAvailable > repayment) {
// The excess amount is distributed between the system and the owner using the reserve ratio
// At this point, we cannot rely on the liquidation price because the challenge might have been started as a
// response to an unreasonable increase of the liquidation price, such that we have to use this heuristic
// for excess fund distribution, which make position owners that maxed out their positions slightly better
// off in comparison to those who did not.
uint256 profits = (reservePPM * (fundsAvailable - repayment)) / 1000_000;
zchf.collectProfits(address(this), profits);
zchf.transfer(owner, fundsAvailable - repayment - profits);
} else if (fundsAvailable < repayment) {
zchf.coverLoss(address(this), repayment - fundsAvailable); // ensure we have enough to pay everything
}
zchf.burnWithoutReserve(repayment, reservePPM); // Repay the challenged part, example: 50 ZCHF leading to 10 ZCHf in implicit profits
return (collateral, offer);
}
function _avertChallenge(Challenge memory _challenge, uint32 number, uint256 liqPrice, uint256 size) internal {
require(block.timestamp != _challenge.start); // do not allow to avert the challenge in the same transaction, see CS-ZCHF-037
if (msg.sender == _challenge.challenger) {
// allow challenger to cancel challenge without paying themselves
} else {
zchf.transferFrom(msg.sender, _challenge.challenger, (size * liqPrice) / (10 ** 18));
}
_challenge.position.notifyChallengeAverted(size);
_challenge.position.collateral().transfer(msg.sender, size);
if (size < _challenge.size) {
challenges[number].size = _challenge.size - size;
} else {
require(size == _challenge.size);
delete challenges[number];
}
}
/**
* @notice Returns 'amount' of the collateral to the challenger and reduces or deletes the relevant challenge.
*/
function _returnChallengerCollateral(Challenge memory _challenge, uint32 number, uint256 amount, bool postpone) internal {
_returnCollateral(_challenge.position.collateral(), _challenge.challenger, amount, postpone);
if (_challenge.size == amount) {
// bid on full amount
delete challenges[number];
} else {
// bid on partial amount
challenges[number].size -= amount;
}
}
/**
* @notice Calculates the current Dutch auction price.
* @dev Starts at the full price at time 'start' and linearly goes to 0 as 'phase2' passes.
*/
function _calculatePrice(uint40 start, uint40 phase2, uint256 liqPrice) internal view returns (uint256) {
uint40 timeNow = uint40(block.timestamp);
if (timeNow <= start) {
return liqPrice;
} else if (timeNow >= start + phase2) {
return 0;
} else {
uint256 timeLeft = phase2 - (timeNow - start);
return (liqPrice / phase2) * timeLeft;
}
}
/**
* @notice Get the price per unit of the collateral for the given challenge.
* @dev The price comes with (36-collateral.decimals()) digits, such that multiplying it with the
* raw collateral amount always yields a price with 36 digits, or 18 digits after dividing by 10**18 again.
*/
function price(uint32 challengeNumber) public view returns (uint256) {
Challenge memory _challenge = challenges[challengeNumber];
if (_challenge.challenger == address(0x0)) {
return 0;
} else {
(uint256 liqPrice, uint40 phase) = _challenge.position.challengeData();
return _calculatePrice(_challenge.start + phase, phase, liqPrice);
}
}
/**
* @notice Challengers can call this method to withdraw collateral whose return was postponed.
*/
function returnPostponedCollateral(address collateral, address target) external {
uint256 amount = pendingReturns[collateral][msg.sender];
delete pendingReturns[collateral][msg.sender];
IERC20(collateral).transfer(target, amount);
}
function _returnCollateral(IERC20 collateral, address recipient, uint256 amount, bool postpone) internal {
if (postpone) {
// Postponing helps in case the challenger was blacklisted or otherwise cannot receive at the moment.
pendingReturns[address(collateral)][recipient] += amount;
emit PostPonedReturn(address(collateral), recipient, amount);
} else {
collateral.transfer(recipient, amount); // return the challenger's collateral
}
}
/**
* The applicable purchase price when forcing the sale of collateral of an expired position.
*
* The price starts at 10x the liquidation price at the expiration time, linearly declines to
* 1x liquidation price over the course of one challenge period, and then linearly declines
* less steeply to 0 over the course of another challenge period.
*/
function expiredPurchasePrice(IPositionV2 pos) public view returns (uint256) {
uint256 liqprice = pos.price();
uint256 expiration = pos.expiration();
if (block.timestamp <= expiration) {
return EXPIRED_PRICE_FACTOR * liqprice;
} else {
uint256 challengePeriod = pos.challengePeriod();
uint256 timePassed = block.timestamp - expiration;
if (timePassed <= challengePeriod) {
// from 10x liquidation price to 1x in first phase
uint256 timeLeft = challengePeriod - timePassed;
return liqprice + (((EXPIRED_PRICE_FACTOR - 1) * liqprice) / challengePeriod) * timeLeft;
} else if (timePassed < 2 * challengePeriod) {
// from 1x liquidation price to 0 in second phase
uint256 timeLeft = 2 * challengePeriod - timePassed;
return (liqprice / challengePeriod) * timeLeft;
} else {
// get collateral for free after both phases passed
return 0;
}
}
}
/**
* Buys up to the desired amount of the collateral asset from the given expired position using
* the applicable 'expiredPurchasePrice' in that instant.
*/
function buyExpiredCollateral(IPositionV2 pos, uint256 upToAmount) external returns (uint256) {
uint256 max = pos.collateral().balanceOf(address(pos));
uint256 amount = upToAmount > max ? max : upToAmount;
uint256 forceSalePrice = expiredPurchasePrice(pos);
uint256 costs = (forceSalePrice * amount) / 10 ** 18;
pos.forceSale(msg.sender, amount, costs);
emit ForcedSale(address(pos), amount, forceSalePrice);
return amount;
}
}
contracts/rate/ILeadrate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ILeadrate {
function currentRatePPM() external view returns (uint24);
function currentTicks() external view returns (uint64);
}
contracts/stablecoin/IBasicFrankencoin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../erc20/IERC20.sol";
import "../equity/IGovernance.sol";
interface IBasicFrankencoin is IERC20 {
function MIN_FEE() external view returns (uint256);
function MIN_APPLICATION_PERIOD() external view returns (uint256);
function suggestMinter(
address _minter,
uint256 _applicationPeriod,
uint256 _applicationFee,
string calldata _message
) external;
function registerPosition(address position) external;
function denyMinter(address minter, address[] calldata helpers, string calldata message) external;
function reserve() external view returns (IGovernance);
function isMinter(address minter) external view returns (bool);
function getPositionParent(address position) external view returns (address);
function mint(address target, uint256 amount) external;
function burnFrom(address target, uint256 amount) external;
function burn(uint256 amount) external;
function coverLoss(address source, uint256 amount) external;
function collectProfits(address source, uint256 _amount) external;
}
contracts/stablecoin/IFrankencoin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../equity/IGovernance.sol";
import "./IBasicFrankencoin.sol";
interface IFrankencoin is IBasicFrankencoin {
function minterReserve() external view returns (uint256);
function calculateAssignedReserve(uint256 mintedAmount, uint32 _reservePPM) external view returns (uint256);
function calculateFreedAmount(uint256 amountExcludingReserve, uint32 reservePPM) external view returns (uint256);
function equity() external view returns (uint256);
function mintWithReserve(address target, uint256 amount, uint32 reservePPM, uint32 feePPM) external;
function burnWithoutReserve(uint256 amountIncludingReserve, uint32 reservePPM) external;
function burnFromWithReserve(address payer, uint256 targetTotalBurnAmount, uint32 _reservePPM) external returns (uint256);
function burnWithReserve(uint256 amountExcludingReserve, uint32 reservePPM) external returns (uint256);
}
contracts/utils/Ownable.sol
// SPDX-License-Identifier: MIT
//
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
//
// Modifications:
// - Replaced Context._msgSender() with msg.sender
// - Made leaner
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
error NotOwner();
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0x0));
address oldOwner = owner;
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function _requireOwner(address sender) internal view {
if (owner != sender) revert NotOwner();
}
modifier onlyOwner() {
_requireOwner(msg.sender);
_;
}
}
Compiler settingsShow
{
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.