contract_name
stringlengths
1
238
file_path
stringlengths
4
23.2k
contract_address
stringlengths
42
42
language
stringclasses
2 values
source_code
stringlengths
1
896k
abi
stringlengths
2
46.2k
compiler_version
stringclasses
297 values
optimization_used
bool
2 classes
runs
float64
1
1,000M
constructor_arguments
stringlengths
0
214k
evm_version
stringclasses
11 values
library
stringclasses
376 values
license_type
stringclasses
16 values
proxy
bool
2 classes
implementation
stringlengths
0
42
swarm_source
stringlengths
0
71
BondedECDSAKeep
solidity/contracts/api/IBondedECDSAKeepFactory.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title Bonded ECDSA Keep Factory /// @notice Factory for Bonded ECDSA Keeps. interface IBondedECDSAKeepFactory { /// @notice Open a new ECDSA Keep. /// @param _groupSize Number of members in the keep. /// @param _honestThreshold Minimum number of honest keep members. /// @param _owner Address of the keep owner. /// @param _bond Value of ETH bond required from the keep. /// @param _stakeLockDuration Stake lock duration in seconds. /// @return Address of the opened keep. function openKeep( uint256 _groupSize, uint256 _honestThreshold, address _owner, uint256 _bond, uint256 _stakeLockDuration ) external payable returns (address keepAddress); /// @notice Gets a fee estimate for opening a new keep. /// @return Uint256 estimate. function openKeepFeeEstimate() external view returns (uint256); /// @notice Gets the total weight of operators /// in the sortition pool for the given application. /// @param _application Address of the application. /// @return The sum of all registered operators' weights in the pool. /// Reverts if sortition pool for the application does not exist. function getSortitionPoolWeight( address _application ) external view returns (uint256); /// @notice Sets the minimum bondable value required from the operator to /// join the sortition pool of the given application. It is up to the /// application to specify a reasonable minimum bond for operators trying to /// join the pool to prevent griefing by operators joining without enough /// bondable value. /// @dev The default minimum bond value for each sortition pool created /// is 20 ETH. /// @param _minimumBondableValue The minimum unbonded value the application /// requires from a single keep. /// @param _groupSize Number of signers in the keep. /// @param _honestThreshold Minimum number of honest keep signers. function setMinimumBondableValue( uint256 _minimumBondableValue, uint256 _groupSize, uint256 _honestThreshold ) external; }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/KeepCreator.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./CloneFactory.sol"; contract KeepCreator is CloneFactory { // Holds the address of the keep contract that will be used as a master // contract for cloning. address public masterKeepAddress; // Keeps created by this factory. address[] public keeps; // Maps keep opened timestamp to each keep address mapping(address => uint256) keepOpenedTimestamp; constructor(address _masterKeepAddress) public { masterKeepAddress = _masterKeepAddress; } /// @notice Gets how many keeps have been opened by this contract. /// @dev Checks the size of the keeps array. /// @return The number of keeps opened so far. function getKeepCount() external view returns (uint256) { return keeps.length; } /// @notice Gets a specific keep address at a given index. /// @return The address of the keep at the given index. function getKeepAtIndex(uint256 index) external view returns (address) { require(index < keeps.length, "Out of bounds."); return keeps[index]; } /// @notice Gets the opened timestamp of the given keep. /// @return Timestamp the given keep was opened at or 0 if this keep /// was not created by this factory. function getKeepOpenedTimestamp(address _keep) external view returns (uint256) { return keepOpenedTimestamp[_keep]; } /// @notice Creates a new keep instance with a clone factory. /// @dev It has to be called by a function implementing a keep opening mechanism. function createKeep() internal returns (address keepAddress) { keepAddress = createClone(masterKeepAddress); keeps.push(keepAddress); /* solium-disable-next-line security/no-block-members*/ keepOpenedTimestamp[keepAddress] = block.timestamp; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/CloneFactory.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly // Implementation of [EIP-1167] based on [clone-factory] // source code. // // EIP 1167: https://eips.ethereum.org/EIPS/eip-1167 // clone-factory: https://github.com/optionality/clone-factory // Modified to use ^0.5.10; instead of ^0.4.23 solidity version // // TODO: This code is copied from tbtc repo. We should consider pulling the code // and tests to a common repo. /* solium-disable */ contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/CandidatesPools.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "@keep-network/sortition-pools/contracts/AbstractSortitionPool.sol"; contract CandidatesPools { // Notification that a new sortition pool has been created. event SortitionPoolCreated( address indexed application, address sortitionPool ); // Mapping of pools with registered member candidates for each application. mapping(address => address) candidatesPools; // application -> candidates pool /// @notice Creates new sortition pool for the application. /// @dev Emits an event after sortition pool creation. /// @param _application Address of the application. /// @return Address of the created sortition pool contract. function createSortitionPool(address _application) external returns (address) { require( candidatesPools[_application] == address(0), "Sortition pool already exists" ); address sortitionPoolAddress = newSortitionPool(_application); candidatesPools[_application] = sortitionPoolAddress; emit SortitionPoolCreated(_application, sortitionPoolAddress); return candidatesPools[_application]; } /// @notice Register caller as a candidate to be selected as keep member /// for the provided customer application. /// @dev If caller is already registered it returns without any changes. /// @param _application Address of the application. function registerMemberCandidate(address _application) external { AbstractSortitionPool candidatesPool = AbstractSortitionPool( getSortitionPool(_application) ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } } /// @notice Checks if operator's details in the member candidates pool are /// up to date for the given application. If not update operator status /// function should be called by the one who is monitoring the status. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorUpToDate(address _operator, address _application) external view returns (bool) { return getSortitionPoolForOperator(_operator, _application) .isOperatorUpToDate(_operator); } /// @notice Invokes update of operator's details in the member candidates pool /// for the given application /// @param _operator Operator's address. /// @param _application Customer application address. function updateOperatorStatus(address _operator, address _application) external { getSortitionPoolForOperator(_operator, _application) .updateOperatorStatus(_operator); } /// @notice Gets the sortition pool address for the given application. /// @dev Reverts if sortition does not exist for the application. /// @param _application Address of the application. /// @return Address of the sortition pool contract. function getSortitionPool(address _application) public view returns (address) { require( candidatesPools[_application] != address(0), "No pool found for the application" ); return candidatesPools[_application]; } /// @notice Checks if operator is registered as a candidate for the given /// customer application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return True if operator is already registered in the candidates pool, /// false otherwise. function isOperatorRegistered(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } AbstractSortitionPool candidatesPool = AbstractSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorRegistered(_operator); } /// @notice Checks if given operator is eligible for the given application. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorEligible(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } AbstractSortitionPool candidatesPool = AbstractSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorEligible(_operator); } /// @notice Gets the total weight of operators /// in the sortition pool for the given application. /// @dev Reverts if sortition does not exits for the application. /// @param _application Address of the application. /// @return The sum of all registered operators' weights in the pool. /// Reverts if sortition pool for the application does not exist. function getSortitionPoolWeight(address _application) public view returns (uint256) { return AbstractSortitionPool(getSortitionPool(_application)).totalWeight(); } /// @notice Creates new sortition pool for the application. /// @dev Have to be implemented by keep factory to call desired sortition /// pool factory. /// @param _application Address of the application. /// @return Address of the created sortition pool contract. function newSortitionPool(address _application) internal returns (address); /// @notice Gets bonded sortition pool of specific application for the /// operator. /// @dev Reverts if the operator is not registered for the application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return Bonded sortition pool. function getSortitionPoolForOperator( address _operator, address _application ) internal view returns (AbstractSortitionPool) { require( isOperatorRegistered(_operator, _application), "Operator not registered for the application" ); return AbstractSortitionPool(candidatesPools[_application]); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/GroupSelectionSeed.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/IRandomBeacon.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; contract GroupSelectionSeed is IRandomBeaconConsumer, ReentrancyGuard { using SafeMath for uint256; IRandomBeacon randomBeacon; // Gas required for a callback from the random beacon. The value specifies // gas required to call `__beaconCallback` function in the worst-case // scenario with all the checks and maximum allowed uint256 relay entry as // a callback parameter. uint256 public constant callbackGas = 30000; // Random beacon sends back callback surplus to the requestor. It may also // decide to send additional request subsidy fee. What's more, it may happen // that the beacon is busy and we will not refresh group selection seed from // the beacon. We accumulate all funds received from the beacon in the // reseed pool and later use this pool to reseed using a public reseed // function on a manual request at any moment. uint256 public reseedPool; uint256 public groupSelectionSeed; constructor(address _randomBeacon) public { randomBeacon = IRandomBeacon(_randomBeacon); // Initial value before the random beacon updates the seed. // https://www.wolframalpha.com/input/?i=pi+to+78+digits groupSelectionSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862; } /// @notice Adds any received funds to the reseed pool. function() external payable { reseedPool += msg.value; } /// @notice Sets a new group selection seed value. /// @dev The function is expected to be called in a callback by the random /// beacon. /// @param _relayEntry Beacon output. function __beaconCallback(uint256 _relayEntry) external onlyRandomBeacon { groupSelectionSeed = _relayEntry; } /// @notice Gets a fee estimate for a new random entry. /// @return Uint256 estimate. function newEntryFeeEstimate() public view returns (uint256) { return randomBeacon.entryFeeEstimate(callbackGas); } /// @notice Calculates the fee requestor has to pay to reseed the factory /// for signer selection. Depending on how much value is stored in the /// reseed pool and the price of a new relay entry, returned value may vary. function newGroupSelectionSeedFee() public view returns (uint256) { uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas); return beaconFee <= reseedPool ? 0 : beaconFee.sub(reseedPool); } /// @notice Reseeds the value used for a signer selection. Requires enough /// payment to be passed. The required payment can be calculated using /// reseedFee function. Factory is automatically triggering reseeding after /// opening a new keep but the reseed can be also triggered at any moment /// using this function. function requestNewGroupSelectionSeed() public payable nonReentrant { reseedPool = reseedPool.add(msg.value); uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas); require(reseedPool >= beaconFee, "Not enough funds to trigger reseed"); reseedPool = reseedPool.sub(beaconFee); (bool success, bytes memory returnData) = requestRelayEntry(beaconFee); if (!success) { revert(string(returnData)); } } /// @notice Updates group selection seed. /// @dev The main goal of this function is to request the random beacon to /// generate a new random number. The beacon generates the number asynchronously /// and will call a callback function when the number is ready. In the meantime /// we update current group selection seed to a new value using a hash function. /// In case of the random beacon request failure this function won't revert /// but add beacon payment to factory's reseed pool. function newGroupSelectionSeed() internal { // Calculate new group selection seed based on the current seed. // We added address of the factory as a key to calculate value different // than sortition pool RNG will, so we don't end up selecting almost // identical group. groupSelectionSeed = uint256( keccak256(abi.encodePacked(groupSelectionSeed, address(this))) ); // Call the random beacon to get a random group selection seed. (bool success, ) = requestRelayEntry(msg.value); if (!success) { reseedPool += msg.value; } } /// @notice Requests for a relay entry using the beacon payment provided as /// the parameter. function requestRelayEntry(uint256 payment) internal returns (bool, bytes memory) { return address(randomBeacon).call.value(payment)( abi.encodeWithSignature( "requestRelayEntry(address,uint256)", address(this), callbackGas ) ); } /// @notice Checks if the caller is the random beacon. /// @dev Throws an error if called by any account other than the random beacon. modifier onlyRandomBeacon() { require( address(randomBeacon) == msg.sender, "Caller is not the random beacon" ); _; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/IRandomBeacon.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title Keep Random Beacon /// /// @notice Keep Random Beacon generates verifiable randomness that is resistant /// to bad actors both in the relay network and on the anchoring blockchain. interface IRandomBeacon { /// @notice Event emitted for each new relay entry generated. It contains /// request ID allowing to associate the generated relay entry with relay /// request created previously with `requestRelayEntry` function. Event is /// emitted no matter if callback was executed or not. /// /// @param requestId Relay request ID for which entry was generated. /// @param entry Generated relay entry. event RelayEntryGenerated(uint256 requestId, uint256 entry); /// @notice Provides the customer with an estimated entry fee in wei to use /// in the request. The fee estimate is only valid for the transaction it is /// called in, so the customer must make the request immediately after /// obtaining the estimate. Insufficient payment will lead to the request /// being rejected and the transaction reverted. /// /// The customer may decide to provide more ether for an entry fee than /// estimated by this function. This is especially helpful when callback gas /// cost fluctuates. Any surplus between the passed fee and the actual cost /// of producing an entry and executing a callback is returned back to the /// customer. /// @param callbackGas Gas required for the callback. function entryFeeEstimate(uint256 callbackGas) external view returns (uint256); /// @notice Submits a request to generate a new relay entry. Executes /// callback on the provided callback contract with the generated entry and /// emits `RelayEntryGenerated(uint256 requestId, uint256 entry)` event. /// Callback contract has to declare public `__beaconCallback(uint256)` /// function that is going to be executed with the result, once ready. /// It is recommended to implement `IRandomBeaconConsumer` interface to /// ensure the correct callback function signature. /// /// @dev Beacon does not support concurrent relay requests. No new requests /// should be made while the beacon is already processing another request. /// Requests made while the beacon is busy will be rejected and the /// transaction reverted. /// /// @param callbackContract Callback contract address. Callback is called /// once a new relay entry has been generated. Must declare public /// `__beaconCallback(uint256)` function. It is recommended to implement /// `IRandomBeaconConsumer` interface to ensure the correct callback function /// signature. /// @param callbackGas Gas required for the callback. /// The customer needs to ensure they provide a sufficient callback gas /// to cover the gas fee of executing the callback. Any surplus is returned /// to the customer. If the callback gas amount turns to be not enough to /// execute the callback, callback execution is skipped. /// @return An uint256 representing uniquely generated relay request ID function requestRelayEntry(address callbackContract, uint256 callbackGas) external payable returns (uint256); /// @notice Submits a request to generate a new relay entry. Emits /// `RelayEntryGenerated(uint256 requestId, uint256 entry)` event for the /// generated entry. /// /// @dev Beacon does not support concurrent relay requests. No new requests /// should be made while the beacon is already processing another request. /// Requests made while the beacon is busy will be rejected and the /// transaction reverted. /// /// @return An uint256 representing uniquely generated relay request ID function requestRelayEntry() external payable returns (uint256); } /// @title Keep Random Beacon Consumer /// /// @notice Receives Keep Random Beacon relay entries with `__beaconCallback` /// function. Contract implementing this interface does not have to be the one /// requesting relay entry but it is the one receiving the requested relay entry /// once it is produced. /// /// @dev Use this interface to indicate the contract receives relay entries from /// the beacon and to ensure the correctness of callback function signature. interface IRandomBeaconConsumer { /// @notice Receives relay entry produced by Keep Random Beacon. This function /// should be called only by Keep Random Beacon. /// /// @param relayEntry Relay entry (random number) produced by Keep Random /// Beacon. function __beaconCallback(uint256 relayEntry) external; }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/BondedSortitionPoolFactory.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./BondedSortitionPool.sol"; import "./api/IBonding.sol"; import "./api/IStaking.sol"; /// @title Bonded Sortition Pool Factory /// @notice Factory for the creation of new bonded sortition pools. contract BondedSortitionPoolFactory { /// @notice Creates a new bonded sortition pool instance. /// @return Address of the new bonded sortition pool contract instance. function createSortitionPool( IStaking stakingContract, IBonding bondingContract, uint256 minimumStake, uint256 initialMinimumBond, uint256 poolWeightDivisor ) public returns (address) { return address( new BondedSortitionPool( stakingContract, bondingContract, minimumStake, initialMinimumBond, poolWeightDivisor, msg.sender ) ); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/BondedSortitionPool.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./AbstractSortitionPool.sol"; import "./RNG.sol"; import "./api/IStaking.sol"; import "./api/IBonding.sol"; import "./DynamicArray.sol"; /// @title Bonded Sortition Pool /// @notice A logarithmic data structure used to store the pool of eligible /// operators weighted by their stakes. It allows to select a group of operators /// based on the provided pseudo-random seed and bonding requirements. /// @dev Keeping pool up to date cannot be done eagerly as proliferation of /// privileged customers could be used to perform DOS attacks by increasing the /// cost of such updates. When a sortition pool prospectively selects an /// operator, the selected operator’s eligibility status and weight needs to be /// checked and, if necessary, updated in the sortition pool. If the changes /// would be detrimental to the operator, the operator selection is performed /// again with the updated input to ensure correctness. /// The pool should specify a reasonable minimum bondable value for operators /// trying to join the pool, to prevent griefing the selection. contract BondedSortitionPool is AbstractSortitionPool { using DynamicArray for DynamicArray.UintArray; using DynamicArray for DynamicArray.AddressArray; using RNG for RNG.State; struct PoolParams { IStaking stakingContract; uint256 minimumStake; IBonding bondingContract; // Defines the minimum unbounded value the operator needs to have to be // eligible to join and stay in the sortition pool. Operators not // satisfying minimum bondable value are removed from the pool. uint256 minimumBondableValue; // Bond required from each operator for the currently pending group // selection. If operator does not have at least this unbounded value, // it is skipped during the selection. uint256 requestedBond; // The weight divisor in the pool can differ from the minimum stake uint256 poolWeightDivisor; address owner; } PoolParams poolParams; constructor( IStaking _stakingContract, IBonding _bondingContract, uint256 _minimumStake, uint256 _minimumBondableValue, uint256 _poolWeightDivisor, address _poolOwner ) public { require(_minimumStake > 0, "Minimum stake cannot be zero"); poolParams = PoolParams( _stakingContract, _minimumStake, _bondingContract, _minimumBondableValue, 0, _poolWeightDivisor, _poolOwner ); } /// @notice Selects a new group of operators of the provided size based on /// the provided pseudo-random seed and bonding requirements. All operators /// in the group are unique. /// /// If there are not enough operators in a pool to form a group or not /// enough operators are eligible for work selection given the bonding /// requirements, the function fails. /// @param groupSize Size of the requested group /// @param seed Pseudo-random number used to select operators to group /// @param minimumStake The current minimum stake value /// @param bondValue Size of the requested bond per operator function selectSetGroup( uint256 groupSize, bytes32 seed, uint256 minimumStake, uint256 bondValue ) public returns (address[] memory) { PoolParams memory params = initializeSelectionParams( minimumStake, bondValue ); require(msg.sender == params.owner, "Only owner may select groups"); uint256 paramsPtr; // solium-disable-next-line security/no-inline-assembly assembly { paramsPtr := params } return generalizedSelectGroup(groupSize, seed, paramsPtr, true); } /// @notice Sets the minimum bondable value required from the operator /// so that it is eligible to be in the pool. The pool should specify /// a reasonable minimum requirement for operators trying to join the pool /// to prevent griefing group selection. /// @param minimumBondableValue The minimum bondable value required from the /// operator. function setMinimumBondableValue(uint256 minimumBondableValue) public { require( msg.sender == poolParams.owner, "Only owner may update minimum bond value" ); poolParams.minimumBondableValue = minimumBondableValue; } /// @notice Returns the minimum bondable value required from the operator /// so that it is eligible to be in the pool. function getMinimumBondableValue() public view returns (uint256) { return poolParams.minimumBondableValue; } function initializeSelectionParams(uint256 minimumStake, uint256 bondValue) internal returns (PoolParams memory params) { params = poolParams; if (params.requestedBond != bondValue) { params.requestedBond = bondValue; } if (params.minimumStake != minimumStake) { params.minimumStake = minimumStake; poolParams.minimumStake = minimumStake; } return params; } // Return the eligible weight of the operator, // which may differ from the weight in the pool. // Return 0 if ineligible. function getEligibleWeight(address operator) internal view returns (uint256) { address ownerAddress = poolParams.owner; // Get the amount of bondable value available for this pool. // We only care that this covers one single bond // regardless of the weight of the operator in the pool. uint256 bondableValue = poolParams.bondingContract.availableUnbondedValue( operator, ownerAddress, address(this) ); // Don't query stake if bond is insufficient. if (bondableValue < poolParams.minimumBondableValue) { return 0; } uint256 eligibleStake = poolParams.stakingContract.eligibleStake( operator, ownerAddress ); // Weight = floor(eligibleStake / poolWeightDivisor) // but only if eligibleStake >= minimumStake. // Ethereum uint256 division performs implicit floor // If eligibleStake < poolWeightDivisor, return 0 = ineligible. if (eligibleStake < poolParams.minimumStake) { return 0; } return (eligibleStake / poolParams.poolWeightDivisor); } function decideFate( uint256 leaf, DynamicArray.AddressArray memory, // `selected`, for future use uint256 paramsPtr ) internal view returns (Fate memory) { PoolParams memory params; // solium-disable-next-line security/no-inline-assembly assembly { params := paramsPtr } address operator = leaf.operator(); uint256 leafWeight = leaf.weight(); if (!isLeafInitialized(leaf)) { return Fate(Decision.Skip, 0); } address ownerAddress = params.owner; // Get the amount of bondable value available for this pool. // We only care that this covers one single bond // regardless of the weight of the operator in the pool. uint256 bondableValue = params.bondingContract.availableUnbondedValue( operator, ownerAddress, address(this) ); // If unbonded value is insufficient for the operator to be in the pool, // delete the operator. if (bondableValue < params.minimumBondableValue) { return Fate(Decision.Delete, 0); } // If unbonded value is sufficient for the operator to be in the pool // but it is not sufficient for the current selection, skip the operator. if (bondableValue < params.requestedBond) { return Fate(Decision.Skip, 0); } uint256 eligibleStake = params.stakingContract.eligibleStake( operator, ownerAddress ); // Weight = floor(eligibleStake / poolWeightDivisor) // Ethereum uint256 division performs implicit floor uint256 eligibleWeight = eligibleStake / params.poolWeightDivisor; if (eligibleWeight < leafWeight || eligibleStake < params.minimumStake) { return Fate(Decision.Delete, 0); } return Fate(Decision.Select, 0); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/api/IBonding.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; interface IBonding { // Gives the amount of ETH // the `operator` has made available for bonding by the `bondCreator`. // If the operator doesn't exist, // or the bond creator isn't authorized, // returns 0. function availableUnbondedValue( address operator, address bondCreator, address authorizedSortitionPool ) external view returns (uint256); }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/api/IStaking.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; interface IStaking { // Gives the amount of KEEP tokens staked by the `operator` // eligible for work selection in the specified `operatorContract`. // // If the operator doesn't exist or hasn't finished initializing, // or the operator contract hasn't been authorized for the operator, // returns 0. function eligibleStake( address operator, address operatorContract ) external view returns (uint256); }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/AbstractSortitionPool.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./GasStation.sol"; import "./RNG.sol"; import "./SortitionTree.sol"; import "./DynamicArray.sol"; import "./api/IStaking.sol"; /// @title Abstract Sortition Pool /// @notice Abstract contract encapsulating common logic of all sortition pools. /// @dev Inheriting implementations are expected to implement getEligibleWeight /// function. contract AbstractSortitionPool is SortitionTree, GasStation { using Leaf for uint256; using Position for uint256; using DynamicArray for DynamicArray.UintArray; using DynamicArray for DynamicArray.AddressArray; using RNG for RNG.State; enum Decision { Select, // Add to the group, and use new seed Skip, // Retry with same seed, skip this leaf Delete, // Retry with same seed, delete this leaf UpdateRetry, // Retry with same seed, update this leaf UpdateSelect // Select and reseed, but also update this leaf } struct Fate { Decision decision; // The new weight of the leaf if Decision is Update*, otherwise 0 uint256 maybeWeight; } // Require 10 blocks after joining before the operator can be selected for // a group. This reduces the degrees of freedom miners and other // front-runners have in conducting pool-bumping attacks. // // We don't use the stack of empty leaves until we run out of space on the // rightmost leaf (i.e. after 2 million operators have joined the pool). // It means all insertions are at the right end, so one can't reorder // operators already in the pool until the pool has been filled once. // Because the index is calculated by taking the minimum number of required // random bits, and seeing if it falls in the range of the total pool weight, // the only scenarios where insertions on the right matter are if it crosses // a power of two threshold for the total weight and unlocks another random // bit, or if a random number that would otherwise be discarded happens to // fall within that space. uint256 constant INIT_BLOCKS = 10; uint256 constant GAS_DEPOSIT_SIZE = 1; /// @notice The number of blocks that must be mined before the operator who // joined the pool is eligible for work selection. function operatorInitBlocks() public pure returns (uint256) { return INIT_BLOCKS; } // Return whether the operator is eligible for the pool. function isOperatorEligible(address operator) public view returns (bool) { return getEligibleWeight(operator) > 0; } // Return whether the operator is present in the pool. function isOperatorInPool(address operator) public view returns (bool) { return getFlaggedLeafPosition(operator) != 0; } // Return whether the operator's weight in the pool // matches their eligible weight. function isOperatorUpToDate(address operator) public view returns (bool) { return getEligibleWeight(operator) == getPoolWeight(operator); } // Returns whether the operator has passed the initialization blocks period // to be eligible for the work selection. Reverts if the operator is not in // the pool. function isOperatorInitialized(address operator) public view returns (bool) { require(isOperatorInPool(operator), "Operator is not in the pool"); uint256 flaggedPosition = getFlaggedLeafPosition(operator); uint256 leafPosition = flaggedPosition.unsetFlag(); uint256 leaf = leaves[leafPosition]; return isLeafInitialized(leaf); } // Return the weight of the operator in the pool, // which may or may not be out of date. function getPoolWeight(address operator) public view returns (uint256) { uint256 flaggedPosition = getFlaggedLeafPosition(operator); if (flaggedPosition == 0) { return 0; } else { uint256 leafPosition = flaggedPosition.unsetFlag(); uint256 leafWeight = leaves[leafPosition].weight(); return leafWeight; } } // Add an operator to the pool, // reverting if the operator is already present. function joinPool(address operator) public { uint256 eligibleWeight = getEligibleWeight(operator); require(eligibleWeight > 0, "Operator not eligible"); depositGas(operator); insertOperator(operator, eligibleWeight); } // Update the operator's weight if present and eligible, // or remove from the pool if present and ineligible. function updateOperatorStatus(address operator) public { uint256 eligibleWeight = getEligibleWeight(operator); uint256 inPoolWeight = getPoolWeight(operator); require(eligibleWeight != inPoolWeight, "Operator already up to date"); if (eligibleWeight == 0) { removeOperator(operator); releaseGas(operator); } else { updateOperator(operator, eligibleWeight); } } function generalizedSelectGroup( uint256 groupSize, bytes32 seed, // This uint256 is actually a void pointer. // We can't pass a SelectionParams, // because the implementation of the SelectionParams struct // can vary between different concrete sortition pool implementations. // // Whatever SelectionParams struct is used by the concrete contract // should be created in the `selectGroup`/`selectSetGroup` function, // then coerced into a uint256 to be passed into this function. // The paramsPtr is then passed to the `decideFate` implementation // which can coerce it back into the concrete SelectionParams. // This allows `generalizedSelectGroup` // to work with any desired eligibility logic. uint256 paramsPtr, bool noDuplicates ) internal returns (address[] memory) { uint256 _root = root; bool rootChanged = false; DynamicArray.AddressArray memory selected; selected = DynamicArray.addressArray(groupSize); RNG.State memory rng; rng = RNG.initialize(seed, _root.sumWeight(), groupSize); while (selected.array.length < groupSize) { rng.generateNewIndex(); (uint256 leafPosition, uint256 startingIndex) = pickWeightedLeaf( rng.currentMappedIndex, _root ); uint256 leaf = leaves[leafPosition]; address operator = leaf.operator(); uint256 leafWeight = leaf.weight(); Fate memory fate = decideFate(leaf, selected, paramsPtr); if (fate.decision == Decision.Select) { selected.arrayPush(operator); if (noDuplicates) { rng.addSkippedInterval(startingIndex, leafWeight); } rng.reseed(seed, selected.array.length); continue; } if (fate.decision == Decision.Skip) { rng.addSkippedInterval(startingIndex, leafWeight); continue; } if (fate.decision == Decision.Delete) { // Update the RNG rng.updateInterval(startingIndex, leafWeight, 0); // Remove the leaf and update root _root = removeLeaf(leafPosition, _root); rootChanged = true; // Remove the record of the operator's leaf and release gas removeLeafPositionRecord(operator); releaseGas(operator); continue; } if (fate.decision == Decision.UpdateRetry) { _root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root); rootChanged = true; rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight); continue; } if (fate.decision == Decision.UpdateSelect) { _root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root); rootChanged = true; selected.arrayPush(operator); rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight); if (noDuplicates) { rng.addSkippedInterval(startingIndex, fate.maybeWeight); } rng.reseed(seed, selected.array.length); continue; } } if (rootChanged) { root = _root; } return selected.array; } function isLeafInitialized(uint256 leaf) internal view returns (bool) { uint256 createdAt = leaf.creationBlock(); return block.number > (createdAt + operatorInitBlocks()); } // Return the eligible weight of the operator, // which may differ from the weight in the pool. // Return 0 if ineligible. function getEligibleWeight(address operator) internal view returns (uint256); function decideFate( uint256 leaf, DynamicArray.AddressArray memory selected, uint256 paramsPtr ) internal view returns (Fate memory); function gasDepositSize() internal pure returns (uint256) { return GAS_DEPOSIT_SIZE; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/RNG.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./Leaf.sol"; import "./Interval.sol"; import "./DynamicArray.sol"; library RNG { using DynamicArray for DynamicArray.UintArray; //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_COUNT = 2**SLOT_BITS; uint256 constant WEIGHT_WIDTH = 256 / SLOT_COUNT; //////////////////////////////////////////////////////////////////////////// struct State { // RNG output uint256 currentMappedIndex; uint256 currentTruncatedIndex; // The random bytes used to derive indices bytes32 currentSeed; // The full range of indices; // generated random numbers are in [0, fullRange). uint256 fullRange; // The truncated range of indices; // how many non-skipped indices are left to consider. // Random indices are generated within this range, // and mapped to the full range by skipping the specified intervals. uint256 truncatedRange; DynamicArray.UintArray skippedIntervals; } function initialize( bytes32 seed, uint256 range, uint256 expectedSkippedCount ) internal view returns (State memory self) { self = State( 0, 0, seed, range, range, DynamicArray.uintArray(expectedSkippedCount) ); reseed(self, seed, 0); return self; } function reseed( State memory self, bytes32 seed, uint256 nonce ) internal view { self.currentSeed = keccak256( abi.encodePacked(seed, nonce, address(this), "reseed") ); } function retryIndex(State memory self) internal view { uint256 truncatedIndex = self.currentTruncatedIndex; if (self.currentTruncatedIndex < self.truncatedRange) { self.currentMappedIndex = Interval.skip( truncatedIndex, self.skippedIntervals ); } else { generateNewIndex(self); } } function updateInterval( State memory self, uint256 startIndex, uint256 oldWeight, uint256 newWeight ) internal pure { int256 weightDiff = int256(newWeight) - int256(oldWeight); uint256 effectiveStartIndex = startIndex + newWeight; self.truncatedRange = uint256(int256(self.truncatedRange) + weightDiff); self.fullRange = uint256(int256(self.fullRange) + weightDiff); Interval.remapIndices( effectiveStartIndex, weightDiff, self.skippedIntervals ); } function addSkippedInterval( State memory self, uint256 startIndex, uint256 weight ) internal pure { self.truncatedRange -= weight; Interval.insert(self.skippedIntervals, Interval.make(startIndex, weight)); } /// @notice Generate a new index based on the current seed, /// without reseeding first. /// This will result in the same truncated index as before /// if it still fits in the current truncated range. function generateNewIndex(State memory self) internal view { uint256 _truncatedRange = self.truncatedRange; require(_truncatedRange > 0, "Not enough operators in pool"); uint256 bits = bitsRequired(_truncatedRange); uint256 truncatedIndex = truncate(bits, uint256(self.currentSeed)); while (truncatedIndex >= _truncatedRange) { self.currentSeed = keccak256( abi.encodePacked(self.currentSeed, address(this), "generate") ); truncatedIndex = truncate(bits, uint256(self.currentSeed)); } self.currentTruncatedIndex = truncatedIndex; self.currentMappedIndex = Interval.skip( truncatedIndex, self.skippedIntervals ); } /// @notice Calculate how many bits are required /// for an index in the range `[0 .. range-1]`. /// /// @param range The upper bound of the desired range, exclusive. /// /// @return uint The smallest number of bits /// that can contain the number `range-1`. function bitsRequired(uint256 range) internal pure returns (uint256) { uint256 bits = WEIGHT_WIDTH - 1; // Left shift by `bits`, // so we have a 1 in the (bits + 1)th least significant bit // and 0 in other bits. // If this number is equal or greater than `range`, // the range [0, range-1] fits in `bits` bits. // // Because we loop from high bits to low bits, // we find the highest number of bits that doesn't fit the range, // and return that number + 1. while (1 << bits >= range) { bits--; } return bits + 1; } /// @notice Truncate `input` to the `bits` least significant bits. function truncate(uint256 bits, uint256 input) internal pure returns (uint256) { return input & ((1 << bits) - 1); } /// @notice Get an index in the range `[0 .. range-1]` /// and the new state of the RNG, /// using the provided `state` of the RNG. /// /// @param range The upper bound of the index, exclusive. /// /// @param state The previous state of the RNG. /// The initial state needs to be obtained /// from a trusted randomness oracle (the random beacon), /// or from a chain of earlier calls to `RNG.getIndex()` /// on an originally trusted seed. /// /// @dev Calculates the number of bits required for the desired range, /// takes the least significant bits of `state` /// and checks if the obtained index is within the desired range. /// The original state is hashed with `keccak256` to get a new state. /// If the index is outside the range, /// the function retries until it gets a suitable index. /// /// @return index A random integer between `0` and `range - 1`, inclusive. /// /// @return newState The new state of the RNG. /// When `getIndex()` is called one or more times, /// care must be taken to always use the output `state` /// of the most recent call as the input `state` of a subsequent call. /// At the end of a transaction calling `RNG.getIndex()`, /// the previous stored state must be overwritten with the latest output. function getIndex(uint256 range, bytes32 state) internal view returns (uint256, bytes32) { uint256 bits = bitsRequired(range); bool found = false; uint256 index = 0; bytes32 newState = state; while (!found) { index = truncate(bits, uint256(newState)); newState = keccak256(abi.encodePacked(newState, address(this))); if (index < range) { found = true; } } return (index, newState); } /// @notice Return an index corresponding to a new, unique leaf. /// /// @dev Gets a new index in a truncated range /// with the weights of all previously selected leaves subtracted. /// This index is then mapped to the full range of possible indices, /// skipping the ranges covered by previous leaves. /// /// @param range The full range in which the unique index should be. /// /// @param state The RNG state. /// /// @param previousLeaves List of indices and weights /// corresponding to the _first_ index of each previously selected leaf, /// and the weight of the same leaf. /// An index number `i` is a starting index of leaf `o` /// if querying for index `i` in the sortition pool returns `o`, /// but querying for `i-1` returns a different leaf. /// This list REALLY needs to be sorted from smallest to largest. /// /// @param sumPreviousWeights The sum of the weights of previous leaves. /// Could be calculated from `previousLeafWeights` /// but providing it explicitly makes the function a bit simpler. /// /// @return uniqueIndex An index in [0, range) that does not overlap /// any of the previousLeaves, /// as determined by the range [index, index + weight). function getUniqueIndex( uint256 range, bytes32 state, uint256[] memory previousLeaves, uint256 sumPreviousWeights ) internal view returns (uint256 uniqueIndex, bytes32 newState) { // Get an index in the truncated range. // The truncated range covers only new leaves, // but has to be mapped to the actual range of indices. uint256 truncatedRange = range - sumPreviousWeights; uint256 truncatedIndex; (truncatedIndex, newState) = getIndex(truncatedRange, state); // Map the truncated index to the available unique indices. uniqueIndex = Interval.skip( truncatedIndex, DynamicArray.convert(previousLeaves) ); return (uniqueIndex, newState); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/SortitionTree.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./StackLib.sol"; import "./Branch.sol"; import "./Position.sol"; import "./Leaf.sol"; contract SortitionTree { using StackLib for uint256[]; using Branch for uint256; using Position for uint256; using Leaf for uint256; //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; uint256 constant LEVELS = 7; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_COUNT = 2**SLOT_BITS; uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT; uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1; uint256 constant POOL_CAPACITY = SLOT_COUNT**LEVELS; //////////////////////////////////////////////////////////////////////////// // implicit tree // root 8 // level2 64 // level3 512 // level4 4k // level5 32k // level6 256k // level7 2M uint256 root; mapping(uint256 => mapping(uint256 => uint256)) branches; mapping(uint256 => uint256) leaves; // the flagged (see setFlag() and unsetFlag() in Position.sol) positions // of all operators present in the pool mapping(address => uint256) flaggedLeafPosition; // the leaf after the rightmost occupied leaf of each stack uint256 rightmostLeaf; // the empty leaves in each stack // between 0 and the rightmost occupied leaf uint256[] emptyLeaves; constructor() public { root = 0; rightmostLeaf = 0; } // checks if operator is already registered in the pool function isOperatorRegistered(address operator) public view returns (bool) { return getFlaggedLeafPosition(operator) != 0; } // Sum the number of operators in each trunk function operatorsInPool() public view returns (uint256) { // Get the number of leaves that might be occupied; // if `rightmostLeaf` equals `firstLeaf()` the tree must be empty, // otherwise the difference between these numbers // gives the number of leaves that may be occupied. uint256 nPossiblyUsedLeaves = rightmostLeaf; // Get the number of empty leaves // not accounted for by the `rightmostLeaf` uint256 nEmptyLeaves = emptyLeaves.getSize(); return (nPossiblyUsedLeaves - nEmptyLeaves); } function totalWeight() public view returns (uint256) { return root.sumWeight(); } function insertOperator(address operator, uint256 weight) internal { require( !isOperatorRegistered(operator), "Operator is already registered in the pool" ); uint256 position = getEmptyLeafPosition(); // Record the block the operator was inserted in uint256 theLeaf = Leaf.make(operator, block.number, weight); root = setLeaf(position, theLeaf, root); // Without position flags, // the position 0x000000 would be treated as empty flaggedLeafPosition[operator] = position.setFlag(); } function removeOperator(address operator) internal { uint256 flaggedPosition = getFlaggedLeafPosition(operator); require(flaggedPosition != 0, "Operator is not registered in the pool"); uint256 unflaggedPosition = flaggedPosition.unsetFlag(); root = removeLeaf(unflaggedPosition, root); removeLeafPositionRecord(operator); } function updateOperator(address operator, uint256 weight) internal { require( isOperatorRegistered(operator), "Operator is not registered in the pool" ); uint256 flaggedPosition = getFlaggedLeafPosition(operator); uint256 unflaggedPosition = flaggedPosition.unsetFlag(); updateLeaf(unflaggedPosition, weight); } function removeLeafPositionRecord(address operator) internal { flaggedLeafPosition[operator] = 0; } function getFlaggedLeafPosition(address operator) internal view returns (uint256) { return flaggedLeafPosition[operator]; } function removeLeaf(uint256 position, uint256 _root) internal returns (uint256) { uint256 rightmostSubOne = rightmostLeaf - 1; bool isRightmost = position == rightmostSubOne; uint256 newRoot = setLeaf(position, 0, _root); if (isRightmost) { rightmostLeaf = rightmostSubOne; } else { emptyLeaves.stackPush(position); } return newRoot; } function updateLeaf(uint256 position, uint256 weight) internal { uint256 oldLeaf = leaves[position]; if (oldLeaf.weight() != weight) { uint256 newLeaf = oldLeaf.setWeight(weight); root = setLeaf(position, newLeaf, root); } } function setLeaf( uint256 position, uint256 theLeaf, uint256 _root ) internal returns (uint256) { uint256 childSlot; uint256 treeNode; uint256 newNode; uint256 nodeWeight = theLeaf.weight(); // set leaf leaves[position] = theLeaf; uint256 parent = position; // set levels 7 to 2 for (uint256 level = LEVELS; level >= 2; level--) { childSlot = parent.slot(); parent = parent.parent(); treeNode = branches[level][parent]; newNode = treeNode.setSlot(childSlot, nodeWeight); branches[level][parent] = newNode; nodeWeight = newNode.sumWeight(); } // set level Root childSlot = parent.slot(); return _root.setSlot(childSlot, nodeWeight); } function pickWeightedLeaf(uint256 index, uint256 _root) internal view returns (uint256 leafPosition, uint256 leafFirstIndex) { uint256 currentIndex = index; uint256 currentNode = _root; uint256 currentPosition = 0; uint256 currentSlot; require(index < currentNode.sumWeight(), "Index exceeds weight"); // get root slot (currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex); // get slots from levels 2 to 7 for (uint256 level = 2; level <= LEVELS; level++) { currentPosition = currentPosition.child(currentSlot); currentNode = branches[level][currentPosition]; (currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex); } // get leaf position leafPosition = currentPosition.child(currentSlot); // get the first index of the leaf // This works because the last weight returned from `pickWeightedSlot()` // equals the "overflow" from getting the current slot. leafFirstIndex = index - currentIndex; } function getEmptyLeafPosition() internal returns (uint256) { uint256 rLeaf = rightmostLeaf; bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY; if (spaceOnRight) { rightmostLeaf = rLeaf + 1; return rLeaf; } else { bool emptyLeavesInStack = leavesInStack(); require(emptyLeavesInStack, "Pool is full"); return emptyLeaves.stackPop(); } } function leavesInStack() internal view returns (bool) { return emptyLeaves.getSize() > 0; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/StackLib.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; library StackLib { function stackPeek(uint256[] storage _array) internal view returns (uint256) { require(_array.length > 0, "No value to peek, array is empty"); return (_array[_array.length - 1]); } function stackPush(uint256[] storage _array, uint256 _element) public { _array.push(_element); } function stackPop(uint256[] storage _array) internal returns (uint256) { require(_array.length > 0, "No value to pop, array is empty"); uint256 value = _array[_array.length - 1]; _array.length -= 1; return value; } function getSize(uint256[] storage _array) internal view returns (uint256) { return _array.length; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/Branch.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; /// @notice The implicit 8-ary trees of the sortition pool /// rely on packing 8 "slots" of 32-bit values into each uint256. /// The Branch library permits efficient calculations on these slots. library Branch { //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_COUNT = 2**SLOT_BITS; uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT; uint256 constant LAST_SLOT = SLOT_COUNT - 1; uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1; //////////////////////////////////////////////////////////////////////////// /// @notice Calculate the right shift required /// to make the 32 least significant bits of an uint256 /// be the bits of the `position`th slot /// when treating the uint256 as a uint32[8]. /// /// @dev Not used for efficiency reasons, /// but left to illustrate the meaning of a common pattern. /// I wish solidity had macros, even C macros. function slotShift(uint256 position) internal pure returns (uint256) { return position * SLOT_WIDTH; } /// @notice Return the `position`th slot of the `node`, /// treating `node` as a uint32[32]. function getSlot(uint256 node, uint256 position) internal pure returns (uint256) { uint256 shiftBits = position * SLOT_WIDTH; // Doing a bitwise AND with `SLOT_MAX` // clears all but the 32 least significant bits. // Because of the right shift by `slotShift(position)` bits, // those 32 bits contain the 32 bits in the `position`th slot of `node`. return (node >> shiftBits) & SLOT_MAX; } /// @notice Return `node` with the `position`th slot set to zero. function clearSlot(uint256 node, uint256 position) internal pure returns (uint256) { uint256 shiftBits = position * SLOT_WIDTH; // Shifting `SLOT_MAX` left by `slotShift(position)` bits // gives us a number where all bits of the `position`th slot are set, // and all other bits are unset. // // Using a bitwise NOT on this number, // we get a uint256 where all bits are set // except for those of the `position`th slot. // // Bitwise ANDing the original `node` with this number // sets the bits of `position`th slot to zero, // leaving all other bits unchanged. return node & ~(SLOT_MAX << shiftBits); } /// @notice Return `node` with the `position`th slot set to `weight`. /// /// @param weight The weight of of the node. /// Safely truncated to a 32-bit number, /// but this should never be called with an overflowing weight regardless. function setSlot( uint256 node, uint256 position, uint256 weight ) internal pure returns (uint256) { uint256 shiftBits = position * SLOT_WIDTH; // Clear the `position`th slot like in `clearSlot()`. uint256 clearedNode = node & ~(SLOT_MAX << shiftBits); // Bitwise AND `weight` with `SLOT_MAX` // to clear all but the 32 least significant bits. // // Shift this left by `slotShift(position)` bits // to obtain a uint256 with all bits unset // except in the `position`th slot // which contains the 32-bit value of `weight`. uint256 shiftedWeight = (weight & SLOT_MAX) << shiftBits; // When we bitwise OR these together, // all other slots except the `position`th one come from the left argument, // and the `position`th gets filled with `weight` from the right argument. return clearedNode | shiftedWeight; } /// @notice Calculate the summed weight of all slots in the `node`. function sumWeight(uint256 node) internal pure returns (uint256 sum) { sum = node & SLOT_MAX; // Iterate through each slot // by shifting `node` right in increments of 32 bits, // and adding the 32 least significant bits to the `sum`. uint256 newNode = node >> SLOT_WIDTH; while (newNode > 0) { sum += (newNode & SLOT_MAX); newNode = newNode >> SLOT_WIDTH; } return sum; } /// @notice Pick a slot in `node` that corresponds to `index`. /// Treats the node like an array of virtual stakers, /// the number of virtual stakers in each slot corresponding to its weight, /// and picks which slot contains the `index`th virtual staker. /// /// @dev Requires that `index` be lower than `sumWeight(node)`. /// However, this is not enforced for performance reasons. /// If `index` exceeds the permitted range, /// `pickWeightedSlot()` returns the rightmost slot /// and an excessively high `newIndex`. /// /// @return slot The slot of `node` containing the `index`th virtual staker. /// /// @return newIndex The index of the `index`th virtual staker of `node` /// within the returned slot. function pickWeightedSlot(uint256 node, uint256 index) internal pure returns (uint256 slot, uint256 newIndex) { newIndex = index; uint256 newNode = node; uint256 currentSlotWeight = newNode & SLOT_MAX; while (newIndex >= currentSlotWeight) { newIndex -= currentSlotWeight; slot++; newNode = newNode >> SLOT_WIDTH; currentSlotWeight = newNode & SLOT_MAX; } return (slot, newIndex); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/Position.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; library Position { //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_POINTER_MAX = (2**SLOT_BITS) - 1; uint256 constant LEAF_FLAG = 1 << 255; //////////////////////////////////////////////////////////////////////////// // Return the last 3 bits of a position number, // corresponding to its slot in its parent function slot(uint256 a) internal pure returns (uint256) { return a & SLOT_POINTER_MAX; } // Return the parent of a position number function parent(uint256 a) internal pure returns (uint256) { return a >> SLOT_BITS; } // Return the location of the child of a at the given slot function child(uint256 a, uint256 s) internal pure returns (uint256) { return (a << SLOT_BITS) | (s & SLOT_POINTER_MAX); // slot(s) } // Return the uint p as a flagged position uint: // the least significant 21 bits contain the position // and the 22nd bit is set as a flag // to distinguish the position 0x000000 from an empty field. function setFlag(uint256 p) internal pure returns (uint256) { return p | LEAF_FLAG; } // Turn a flagged position into an unflagged position // by removing the flag at the 22nd least significant bit. // // We shouldn't _actually_ need this // as all position-manipulating code should ignore non-position bits anyway // but it's cheap to call so might as well do it. function unsetFlag(uint256 p) internal pure returns (uint256) { return p & (~LEAF_FLAG); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/Leaf.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; library Leaf { //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_COUNT = 2**SLOT_BITS; uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT; uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1; uint256 constant WEIGHT_WIDTH = SLOT_WIDTH; uint256 constant WEIGHT_MAX = SLOT_MAX; uint256 constant BLOCKHEIGHT_WIDTH = 96 - WEIGHT_WIDTH; uint256 constant BLOCKHEIGHT_MAX = (2**BLOCKHEIGHT_WIDTH) - 1; //////////////////////////////////////////////////////////////////////////// function make( address _operator, uint256 _creationBlock, uint256 _weight ) internal pure returns (uint256) { // Converting a bytesX type into a larger type // adds zero bytes on the right. uint256 op = uint256(bytes32(bytes20(_operator))); // Bitwise AND the weight to erase // all but the 32 least significant bits uint256 wt = _weight & WEIGHT_MAX; // Erase all but the 64 least significant bits, // then shift left by 32 bits to make room for the weight uint256 cb = (_creationBlock & BLOCKHEIGHT_MAX) << WEIGHT_WIDTH; // Bitwise OR them all together to get // [address operator || uint64 creationBlock || uint32 weight] return (op | cb | wt); } function operator(uint256 leaf) internal pure returns (address) { // Converting a bytesX type into a smaller type // truncates it on the right. return address(bytes20(bytes32(leaf))); } /// @notice Return the block number the leaf was created in. function creationBlock(uint256 leaf) internal pure returns (uint256) { return ((leaf >> WEIGHT_WIDTH) & BLOCKHEIGHT_MAX); } function weight(uint256 leaf) internal pure returns (uint256) { // Weight is stored in the 32 least significant bits. // Bitwise AND ensures that we only get the contents of those bits. return (leaf & WEIGHT_MAX); } function setWeight(uint256 leaf, uint256 newWeight) internal pure returns (uint256) { return ((leaf & ~WEIGHT_MAX) | (newWeight & WEIGHT_MAX)); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/sortition-pools/contracts/Interval.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "./Leaf.sol"; import "./DynamicArray.sol"; library Interval { using DynamicArray for DynamicArray.UintArray; //////////////////////////////////////////////////////////////////////////// // Parameters for configuration // How many bits a position uses per level of the tree; // each branch of the tree contains 2**SLOT_BITS slots. uint256 constant SLOT_BITS = 3; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Derived constants, do not touch uint256 constant SLOT_COUNT = 2**SLOT_BITS; uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT; uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1; uint256 constant WEIGHT_WIDTH = SLOT_WIDTH; uint256 constant WEIGHT_MAX = SLOT_MAX; uint256 constant START_INDEX_WIDTH = WEIGHT_WIDTH; uint256 constant START_INDEX_MAX = WEIGHT_MAX; uint256 constant START_INDEX_SHIFT = WEIGHT_WIDTH; //////////////////////////////////////////////////////////////////////////// // Interval stores information about a selected interval // inside a single uint256 in a manner similar to Leaf // but optimized for use within group selection // // The information stored consists of: // - weight // - starting index function make(uint256 startingIndex, uint256 weight) internal pure returns (uint256) { uint256 idx = (startingIndex & START_INDEX_MAX) << START_INDEX_SHIFT; uint256 wt = weight & WEIGHT_MAX; return (idx | wt); } function opWeight(uint256 op) internal pure returns (uint256) { return (op & WEIGHT_MAX); } // Return the starting index of the interval function index(uint256 a) internal pure returns (uint256) { return ((a >> WEIGHT_WIDTH) & START_INDEX_MAX); } function setIndex(uint256 op, uint256 i) internal pure returns (uint256) { uint256 shiftedIndex = ((i & START_INDEX_MAX) << WEIGHT_WIDTH); return (op & (~(START_INDEX_MAX << WEIGHT_WIDTH))) | shiftedIndex; } function insert(DynamicArray.UintArray memory intervals, uint256 interval) internal pure { uint256 tempInterval = interval; for (uint256 i = 0; i < intervals.array.length; i++) { uint256 thisInterval = intervals.array[i]; // We can compare the raw underlying uint256 values // because the starting index is stored // in the most significant nonzero bits. if (tempInterval < thisInterval) { intervals.array[i] = tempInterval; tempInterval = thisInterval; } } intervals.arrayPush(tempInterval); } function skip(uint256 truncatedIndex, DynamicArray.UintArray memory intervals) internal pure returns (uint256 mappedIndex) { mappedIndex = truncatedIndex; for (uint256 i = 0; i < intervals.array.length; i++) { uint256 interval = intervals.array[i]; // If the index is greater than the starting index of the `i`th leaf, // we need to skip that leaf. if (mappedIndex >= index(interval)) { // Add the weight of this previous leaf to the index, // ensuring that we skip the leaf. mappedIndex += Leaf.weight(interval); } else { break; } } return mappedIndex; } /// @notice Recalculate the starting indices of the previousLeaves /// when an interval is removed or added at the specified index. /// @dev Applies weightDiff to each starting index in previousLeaves /// that exceeds affectedStartingIndex. /// @param affectedStartingIndex The starting index of the interval. /// @param weightDiff The difference in weight; /// negative for a deleted interval, /// positive for an added interval. /// @param previousLeaves The starting indices and weights /// of the previously selected leaves. /// @return The starting indices of the previous leaves /// in a tree with the affected interval updated. function remapIndices( uint256 affectedStartingIndex, int256 weightDiff, DynamicArray.UintArray memory previousLeaves ) internal pure { uint256 nPreviousLeaves = previousLeaves.array.length; for (uint256 i = 0; i < nPreviousLeaves; i++) { uint256 interval = previousLeaves.array[i]; uint256 startingIndex = index(interval); // If index is greater than the index of the affected interval, // update the starting index by the weight change. if (startingIndex > affectedStartingIndex) { uint256 newIndex = uint256(int256(startingIndex) + weightDiff); previousLeaves.array[i] = setIndex(interval, newIndex); } } } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/KeepRegistry.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; /// @title KeepRegistry /// @notice Governance owned registry of approved contracts and roles. contract KeepRegistry { enum ContractStatus {New, Approved, Disabled} // Governance role is to enable recovery from key compromise by rekeying // other roles. Also, it can disable operator contract panic buttons // permanently. address public governance; // Registry Keeper maintains approved operator contracts. Each operator // contract must be approved before it can be authorized by a staker or // used by a service contract. address public registryKeeper; // Each operator contract has a Panic Button which can disable malicious // or malfunctioning contract that have been previously approved by the // Registry Keeper. // // New operator contract added to the registry has a default panic button // value assigned (defaultPanicButton). Panic button for each operator // contract can be later updated by Governance to individual value. // // It is possible to disable panic button for individual contract by // setting the panic button to zero address. In such case, operator contract // can not be disabled and is permanently approved in the registry. mapping(address => address) public panicButtons; // Default panic button for each new operator contract added to the // registry. Can be later updated for each contract. address public defaultPanicButton; // Each service contract has a Operator Contract Upgrader whose purpose // is to manage operator contracts for that specific service contract. // The Operator Contract Upgrader can add new operator contracts to the // service contract’s operator contract list, and deprecate old ones. mapping(address => address) public operatorContractUpgraders; // Operator contract may have a Service Contract Upgrader whose purpose is // to manage service contracts for that specific operator contract. // Service Contract Upgrader can add and remove service contracts // from the list of service contracts approved to work with the operator // contract. List of service contracts is maintained in the operator // contract and is optional - not every operator contract needs to have // a list of service contracts it wants to cooperate with. mapping(address => address) public serviceContractUpgraders; // The registry of operator contracts mapping(address => ContractStatus) public operatorContracts; event OperatorContractApproved(address operatorContract); event OperatorContractDisabled(address operatorContract); event GovernanceUpdated(address governance); event RegistryKeeperUpdated(address registryKeeper); event DefaultPanicButtonUpdated(address defaultPanicButton); event OperatorContractPanicButtonDisabled(address operatorContract); event OperatorContractPanicButtonUpdated( address operatorContract, address panicButton ); event OperatorContractUpgraderUpdated( address serviceContract, address upgrader ); event ServiceContractUpgraderUpdated( address operatorContract, address keeper ); modifier onlyGovernance() { require(governance == msg.sender, "Not authorized"); _; } modifier onlyRegistryKeeper() { require(registryKeeper == msg.sender, "Not authorized"); _; } modifier onlyPanicButton(address _operatorContract) { address panicButton = panicButtons[_operatorContract]; require(panicButton != address(0), "Panic button disabled"); require(panicButton == msg.sender, "Not authorized"); _; } modifier onlyForNewContract(address _operatorContract) { require( isNewOperatorContract(_operatorContract), "Not a new operator contract" ); _; } modifier onlyForApprovedContract(address _operatorContract) { require( isApprovedOperatorContract(_operatorContract), "Not an approved operator contract" ); _; } constructor() public { governance = msg.sender; registryKeeper = msg.sender; defaultPanicButton = msg.sender; } function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceUpdated(governance); } function setRegistryKeeper(address _registryKeeper) public onlyGovernance { registryKeeper = _registryKeeper; emit RegistryKeeperUpdated(registryKeeper); } function setDefaultPanicButton(address _panicButton) public onlyGovernance { defaultPanicButton = _panicButton; emit DefaultPanicButtonUpdated(defaultPanicButton); } function setOperatorContractPanicButton( address _operatorContract, address _panicButton ) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Disabled panic button cannot be updated" ); require( _panicButton != address(0), "Panic button must be non-zero address" ); panicButtons[_operatorContract] = _panicButton; emit OperatorContractPanicButtonUpdated( _operatorContract, _panicButton ); } function disableOperatorContractPanicButton(address _operatorContract) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Panic button already disabled" ); panicButtons[_operatorContract] = address(0); emit OperatorContractPanicButtonDisabled(_operatorContract); } function setOperatorContractUpgrader( address _serviceContract, address _operatorContractUpgrader ) public onlyGovernance { operatorContractUpgraders[_serviceContract] = _operatorContractUpgrader; emit OperatorContractUpgraderUpdated( _serviceContract, _operatorContractUpgrader ); } function setServiceContractUpgrader( address _operatorContract, address _serviceContractUpgrader ) public onlyGovernance { serviceContractUpgraders[_operatorContract] = _serviceContractUpgrader; emit ServiceContractUpgraderUpdated( _operatorContract, _serviceContractUpgrader ); } function approveOperatorContract(address operatorContract) public onlyForNewContract(operatorContract) onlyRegistryKeeper { operatorContracts[operatorContract] = ContractStatus.Approved; panicButtons[operatorContract] = defaultPanicButton; emit OperatorContractApproved(operatorContract); } function disableOperatorContract(address operatorContract) public onlyForApprovedContract(operatorContract) onlyPanicButton(operatorContract) { operatorContracts[operatorContract] = ContractStatus.Disabled; emit OperatorContractDisabled(operatorContract); } function isNewOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.New; } function isApprovedOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.Approved; } function operatorContractUpgraderFor(address _serviceContract) public view returns (address) { return operatorContractUpgraders[_serviceContract]; } function serviceContractUpgraderFor(address _operatorContract) public view returns (address) { return serviceContractUpgraders[_operatorContract]; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/Authorizations.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./KeepRegistry.sol"; /// @title AuthorityDelegator /// @notice An operator contract can delegate authority to other operator /// contracts by implementing the AuthorityDelegator interface. /// /// To delegate authority, /// the recipient of delegated authority must call `claimDelegatedAuthority`, /// specifying the contract it wants delegated authority from. /// The staking contract calls `delegator.__isRecognized(recipient)` /// and if the call returns `true`, /// the named delegator contract is set as the recipient's authority delegator. /// Any future checks of registry approval or per-operator authorization /// will transparently mirror the delegator's status. /// /// Authority can be delegated recursively; /// an operator contract receiving delegated authority /// can recognize other operator contracts as recipients of its authority. interface AuthorityDelegator { function __isRecognized(address delegatedAuthorityRecipient) external returns (bool); } /// @title AuthorityVerifier /// @notice An operator contract can delegate authority to other operator /// contracts. Entry in the registry is not updated and source contract remains /// listed there as authorized. This interface is a verifier that support verification /// of contract authorization in case of authority delegation from the source contract. interface AuthorityVerifier { /// @notice Returns true if the given operator contract has been approved /// for use. The function never reverts. function isApprovedOperatorContract(address _operatorContract) external view returns (bool); } contract Authorizations is AuthorityVerifier { // Authorized operator contracts. mapping(address => mapping (address => bool)) internal authorizations; // Granters of delegated authority to operator contracts. // E.g. keep factories granting delegated authority to keeps. // `delegatedAuthority[keep] = factory` mapping(address => address) internal delegatedAuthority; // Registry contract with a list of approved operator contracts and upgraders. KeepRegistry internal registry; modifier onlyApprovedOperatorContract(address operatorContract) { require( isApprovedOperatorContract(operatorContract), "Operator contract unapproved" ); _; } constructor(KeepRegistry _registry) public { registry = _registry; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address); /// @notice Authorizes operator contract to access staked token balance of /// the provided operator. Can only be executed by stake operator authorizer. /// Contracts using delegated authority /// cannot be authorized with `authorizeOperatorContract`. /// Instead, authorize `getAuthoritySource(_operatorContract)`. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function authorizeOperatorContract(address _operator, address _operatorContract) public onlyApprovedOperatorContract(_operatorContract) { require( authorizerOf(_operator) == msg.sender, "Not operator authorizer" ); require( getAuthoritySource(_operatorContract) == _operatorContract, "Delegated authority used" ); authorizations[_operatorContract][_operator] = true; } /// @notice Checks if operator contract has access to the staked token balance of /// the provided operator. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool) { return authorizations[getAuthoritySource(_operatorContract)][_operator]; } /// @notice Grant the sender the same authority as `delegatedAuthoritySource` /// @dev If `delegatedAuthoritySource` is an approved operator contract /// and recognizes the claimant, this relationship will be recorded in /// `delegatedAuthority`. Later, the claimant can slash, seize, place locks etc. /// on operators that have authorized the `delegatedAuthoritySource`. /// If the `delegatedAuthoritySource` is disabled with the panic button, /// any recipients of delegated authority from it will also be disabled. function claimDelegatedAuthority( address delegatedAuthoritySource ) public onlyApprovedOperatorContract(delegatedAuthoritySource) { require( AuthorityDelegator(delegatedAuthoritySource).__isRecognized(msg.sender), "Unrecognized claimant" ); delegatedAuthority[msg.sender] = delegatedAuthoritySource; } /// @notice Checks if the operator contract is authorized in the registry. /// If the contract uses delegated authority it checks authorization of the /// source contract. /// @param _operatorContract address of operator contract. /// @return True if operator contract is approved, false if operator contract /// has not been approved or if it was disabled by the panic button. function isApprovedOperatorContract(address _operatorContract) public view returns (bool) { return registry.isApprovedOperatorContract( getAuthoritySource(_operatorContract) ); } /// @notice Get the source of the operator contract's authority. /// If the contract uses delegated authority, /// returns the original source of the delegated authority. /// If the contract doesn't use delegated authority, /// returns the contract itself. /// Authorize `getAuthoritySource(operatorContract)` /// to grant `operatorContract` the authority to penalize an operator. function getAuthoritySource( address operatorContract ) public view returns (address) { address delegatedAuthoritySource = delegatedAuthority[operatorContract]; if (delegatedAuthoritySource == address(0)) { return operatorContract; } return getAuthoritySource(delegatedAuthoritySource); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/grant/UnlockingSchedule.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library UnlockingSchedule { using SafeMath for uint256; function getUnlockedAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff ) internal pure returns (uint256) { bool cliffNotReached = _now < cliff; if (cliffNotReached) { return 0; } uint256 timeElapsed = _now.sub(start); bool unlockingPeriodFinished = timeElapsed >= duration; if (unlockingPeriodFinished) { return grantedAmount; } return grantedAmount.mul(timeElapsed).div(duration); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; library AddressArrayUtils { function contains(address[] memory self, address _address) internal pure returns (bool) { for (uint i = 0; i < self.length; i++) { if (_address == self[i]) { return true; } } return false; } function removeAddress(address[] storage self, address _addressToRemove) internal returns (address[] storage) { for (uint i = 0; i < self.length; i++) { // If address is found in array. if (_addressToRemove == self[i]) { // Delete element at index and shift array. for (uint j = i; j < self.length-1; j++) { self[j] = self[j+1]; } self.length--; i--; } } return self; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/GrantStakingPolicy.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; /// @title GrantStakingPolicy /// @notice A staking policy defines the function `getStakeableAmount` /// which calculates how many tokens may be staked from a token grant. contract GrantStakingPolicy { function getStakeableAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff, uint256 withdrawn) public view returns (uint256); }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/TokenStakingEscrow.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./KeepToken.sol"; import "./utils/BytesLib.sol"; import "./TokenGrant.sol"; import "./ManagedGrant.sol"; import "./TokenSender.sol"; /// @title TokenStakingEscrow /// @notice Escrow lets the staking contract to deposit undelegated, granted /// tokens and either withdraw them based on the grant unlocking schedule or /// re-delegate them to another operator. /// @dev The owner of TokenStakingEscrow is TokenStaking contract and only owner /// can deposit. This contract works with an assumption that operator is unique /// in the scope of `TokenStaking`, that is, no more than one delegation in the /// `TokenStaking` can be done do the given operator ever. Even if the previous /// delegation ended, operator address cannot be reused. contract TokenStakingEscrow is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using BytesLib for bytes; using UnlockingSchedule for uint256; event Deposited( address indexed operator, uint256 indexed grantId, uint256 amount ); event DepositRedelegated( address indexed previousOperator, address indexed newOperator, uint256 indexed grantId, uint256 amount ); event DepositWithdrawn( address indexed operator, address indexed grantee, uint256 amount ); event RevokedDepositWithdrawn( address indexed operator, address indexed grantManager, uint256 amount ); event EscrowAuthorized( address indexed grantManager, address escrow ); IERC20 public keepToken; TokenGrant public tokenGrant; struct Deposit { uint256 grantId; uint256 amount; uint256 withdrawn; uint256 redelegated; } // operator address -> KEEP deposit mapping(address => Deposit) internal deposits; // Other escrows authorized by grant manager. Grantee may request to migrate // tokens to another authorized escrow. // grant manager -> escrow -> authorized? mapping(address => mapping (address => bool)) internal authorizedEscrows; constructor( KeepToken _keepToken, TokenGrant _tokenGrant ) public { keepToken = _keepToken; tokenGrant = _tokenGrant; } /// @notice receiveApproval accepts deposits from staking contract and /// stores them in the escrow by the operator address from which they were /// undelegated. Function expects operator address and grant identifier to /// be passed as ABI-encoded information in extraData. Grant with the given /// identifier has to exist. /// @param from Address depositing tokens - it has to be the address of /// TokenStaking contract owning TokenStakingEscrow. /// @param value The amount of KEEP tokens deposited. /// @param token The address of KEEP token contract. /// @param extraData ABI-encoded data containing operator address (32 bytes) /// and grant ID (32 bytes). function receiveApproval( address from, uint256 value, address token, bytes memory extraData ) public { require(IERC20(token) == keepToken, "Not a KEEP token"); require(msg.sender == token, "KEEP token is not the sender"); require(extraData.length == 64, "Unexpected data length"); (address operator, uint256 grantId) = abi.decode( extraData, (address, uint256) ); receiveDeposit(from, value, operator, grantId); } /// @notice Redelegates deposit or part of the deposit to another operator. /// Uses the same staking contract as the original delegation. /// @param previousOperator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @dev Only grantee is allowed to call this function. For managed grant, /// caller has to be the managed grantee. /// @param amount Amount of tokens to delegate. /// @param extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function redelegate( address previousOperator, uint256 amount, bytes memory extraData ) public { require(extraData.length == 60, "Corrupted delegation data"); Deposit memory deposit = deposits[previousOperator]; uint256 grantId = deposit.grantId; address newOperator = extraData.toAddress(20); require(isGrantee(msg.sender, grantId), "Not authorized"); require(getAmountRevoked(grantId) == 0, "Grant revoked"); require( availableAmount(previousOperator) >= amount, "Insufficient balance" ); require( !hasDeposit(newOperator), "Redelegating to previously used operator is not allowed" ); deposits[previousOperator].redelegated = deposit.redelegated.add(amount); TokenSender(address(keepToken)).approveAndCall( owner(), // TokenStaking contract associated with the escrow amount, abi.encodePacked(extraData, grantId) ); emit DepositRedelegated( previousOperator, newOperator, grantId, amount ); } /// @notice Returns true if there is a deposit for the given operator in /// the escrow. Otherwise, returns false. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function hasDeposit(address operator) public view returns (bool) { return depositedAmount(operator) > 0; } /// @notice Returns the currently available amount deposited in the escrow /// that may or may not be currently withdrawable. The available amount /// is the amount initially deposited minus the amount withdrawn and /// redelegated so far from that deposit. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function availableAmount(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; return deposit.amount.sub(deposit.withdrawn).sub(deposit.redelegated); } /// @notice Returns the total amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositedAmount(address operator) public view returns (uint256) { return deposits[operator].amount; } /// @notice Returns grant ID for the amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositGrantId(address operator) public view returns (uint256) { return deposits[operator].grantId; } /// @notice Returns the amount withdrawn so far from the value deposited /// in the escrow contract after undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositWithdrawnAmount(address operator) public view returns (uint256) { return deposits[operator].withdrawn; } /// @notice Returns the total amount redelegated so far from the value /// deposited in the escrow contract after undelegating it from the provided /// operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositRedelegatedAmount(address operator) public view returns (uint256) { return deposits[operator].redelegated; } /// @notice Returns the currently withdrawable amount that was previously /// deposited in the escrow after undelegating it from the provided operator. /// Tokens are unlocked based on their grant unlocking schedule. /// Function returns 0 for non-existing deposits and revoked grants if they /// have been revoked before they fully unlocked. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawable(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; // Staked tokens can be only withdrawn by grantee for non-revoked grant // assuming that grant has not fully unlocked before it's been // revoked. // // It is not possible for the escrow to determine the number of tokens // it should return to the grantee of a revoked grant given different // possible staking contracts and staking policies. // // If the entire grant unlocked before it's been reverted, escrow // lets to withdraw the entire deposited amount. if (getAmountRevoked(deposit.grantId) == 0) { ( uint256 duration, uint256 start, uint256 cliff ) = getUnlockingSchedule(deposit.grantId); uint256 unlocked = now.getUnlockedAmount( deposit.amount, duration, start, cliff ); if (deposit.withdrawn.add(deposit.redelegated) < unlocked) { return unlocked.sub(deposit.withdrawn).sub(deposit.redelegated); } } return 0; } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. Important: this function can not be /// called for a `ManagedGrant` grantee. This may lead to locking tokens. /// For `ManagedGrant`, please use `withdrawToManagedGrantee` instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdraw(address operator) public { Deposit memory deposit = deposits[operator]; address grantee = getGrantee(deposit.grantId); // Make sure this function is not called for a managed grant. // If called for a managed grant, tokens could be locked there. // Better be safe than sorry. (bool success, ) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); require(!success, "Can not be called for managed grant"); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. This function works only for /// `ManagedGrant` grantees. For a standard grant, please use `withdraw` /// instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawToManagedGrantee(address operator) public { Deposit memory deposit = deposits[operator]; address managedGrant = getGrantee(deposit.grantId); address grantee = getManagedGrantee(managedGrant); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Migrates all available tokens to another authorized escrow. /// Can be requested only by grantee. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @param receivingEscrow Escrow to which tokens should be migrated. /// @dev The receiving escrow needs to accept deposits from this escrow, at /// least for the period of migration. function migrate( address operator, address receivingEscrow ) public { Deposit memory deposit = deposits[operator]; require(isGrantee(msg.sender, deposit.grantId), "Not authorized"); address grantManager = getGrantManager(deposit.grantId); require( authorizedEscrows[grantManager][receivingEscrow], "Escrow not authorized" ); uint256 amountLeft = availableAmount(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amountLeft); TokenSender(address(keepToken)).approveAndCall( receivingEscrow, amountLeft, abi.encode(operator, deposit.grantId) ); } /// @notice Withdraws the entire amount that is still deposited in the /// escrow in case the grant has been revoked. Anyone can call this function /// and the entire amount is transferred back to the grant manager. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawRevoked(address operator) public { Deposit memory deposit = deposits[operator]; require( getAmountRevoked(deposit.grantId) > 0, "No revoked tokens to withdraw" ); address grantManager = getGrantManager(deposit.grantId); withdrawRevoked(deposit, operator, grantManager); } /// @notice Used by grant manager to authorize another escrows for // funds migration. function authorizeEscrow(address anotherEscrow) public { require( anotherEscrow != address(0x0), "Escrow address can't be zero" ); authorizedEscrows[msg.sender][anotherEscrow] = true; emit EscrowAuthorized(msg.sender, anotherEscrow); } /// @notice Resolves the final grantee of ManagedGrant contract. If the /// provided address is not a ManagedGrant contract, function reverts. /// @param managedGrant Address of the managed grant contract. function getManagedGrantee( address managedGrant ) public view returns(address) { ManagedGrant grant = ManagedGrant(managedGrant); return grant.grantee(); } function receiveDeposit( address from, uint256 value, address operator, uint256 grantId ) internal { // This contract works with an assumption that operator is unique. // This is fine as long as the staking contract works with the same // assumption so we are limiting deposits to the staking contract only. require(from == owner(), "Only owner can deposit"); require( getAmountGranted(grantId) > 0, "Grant with this ID does not exist" ); require( !hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); keepToken.safeTransferFrom(from, address(this), value); deposits[operator] = Deposit(grantId, value, 0, 0); emit Deposited(operator, grantId, value); } function isGrantee( address maybeGrantee, uint256 grantId ) internal returns (bool) { // Let's check the simplest case first - standard grantee. // If the given address is set as a grantee for grant with the given ID, // we return true. address grantee = getGrantee(grantId); if (maybeGrantee == grantee) { return true; } // If the given address is not a standard grantee, there is still // a chance that address is a managed grantee. We are calling // getManagedGrantee that will cast the grantee to ManagedGrant and try // to call getGrantee() function. If this call returns non-zero address, // it means we are dealing with a ManagedGrant. (, bytes memory result) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); if (result.length == 0) { return false; } // At this point we know we are dealing with a ManagedGrant, so the last // thing we need to check is whether the managed grantee of that grant // is the grantee address passed as a parameter. address managedGrantee = abi.decode(result, (address)); return maybeGrantee == managedGrantee; } function withdraw( Deposit memory deposit, address operator, address grantee ) internal { uint256 amount = withdrawable(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amount); keepToken.safeTransfer(grantee, amount); emit DepositWithdrawn(operator, grantee, amount); } function withdrawRevoked( Deposit memory deposit, address operator, address grantManager ) internal { uint256 amount = availableAmount(operator); deposits[operator].withdrawn = amount; keepToken.safeTransfer(grantManager, amount); emit RevokedDepositWithdrawn(operator, grantManager, amount); } function getAmountGranted(uint256 grantId) internal view returns ( uint256 amountGranted ) { (amountGranted,,,,,) = tokenGrant.getGrant(grantId); } function getAmountRevoked(uint256 grantId) internal view returns ( uint256 amountRevoked ) { (,,,amountRevoked,,) = tokenGrant.getGrant(grantId); } function getUnlockingSchedule(uint256 grantId) internal view returns ( uint256 duration, uint256 start, uint256 cliff ) { (,duration,start,cliff,) = tokenGrant.getGrantUnlockingSchedule(grantId); } function getGrantee(uint256 grantId) internal view returns ( address grantee ) { (,,,,,grantee) = tokenGrant.getGrant(grantId); } function getGrantManager(uint256 grantId) internal view returns ( address grantManager ) { (grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/TokenSender.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; /// @dev Interface of sender contract for approveAndCall pattern. interface TokenSender { function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external; }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/KeepToken.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; /// @dev Interface of recipient contract for approveAndCall pattern. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /// @title KEEP Token /// @dev Standard ERC20Burnable token contract KeepToken is ERC20Burnable, ERC20Detailed { string public constant NAME = "KEEP Token"; string public constant SYMBOL = "KEEP"; uint8 public constant DECIMALS = 18; // The number of digits after the decimal place when displaying token values on-screen. uint256 public constant INITIAL_SUPPLY = 10**27; // 1 billion tokens, 18 decimal places. /// @dev Gives msg.sender all of existing tokens. constructor() public ERC20Detailed(NAME, SYMBOL, DECIMALS) { _mint(msg.sender, INITIAL_SUPPLY); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` tokens /// on your behalf and then ping the contract about it. /// @param _spender The address authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/RolesLookup.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "../utils/AddressArrayUtils.sol"; import "../StakeDelegatable.sol"; import "../TokenGrant.sol"; import "../ManagedGrant.sol"; /// @title Roles Lookup /// @notice Library facilitating lookup of roles in stake delegation setup. library RolesLookup { using AddressArrayUtils for address[]; /// @notice Returns true if the tokenOwner delegated tokens to operator /// using the provided stakeDelegatable contract. Othwerwise, returns false. /// This function works only for the case when tokenOwner own those tokens /// and those are not tokens from a grant. function isTokenOwnerForOperator( address tokenOwner, address operator, StakeDelegatable stakeDelegatable ) internal view returns (bool) { return stakeDelegatable.ownerOf(operator) == tokenOwner; } /// @notice Returns true if the grantee delegated tokens to operator /// with the provided tokenGrant contract. Otherwise, returns false. /// This function works only for the case when tokens were generated from /// a non-managed grant, that is, the grantee is a non-contract address to /// which the delegated tokens were granted. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isGranteeForOperator( address grantee, address operator, TokenGrant tokenGrant ) internal view returns (bool) { address[] memory operators = tokenGrant.getGranteeOperators(grantee); return operators.contains(operator); } /// @notice Returns true if the grantee from the given managed grant contract /// delegated tokens to operator with the provided tokenGrant contract. /// Otherwise, returns false. In case the grantee declared by the managed /// grant contract does not match the provided grantee, function reverts. /// This function works only for cases when grantee, from TokenGrant's /// perspective, is a smart contract exposing grantee() function returning /// the final grantee. One possibility is the ManagedGrant contract. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isManagedGranteeForOperator( address grantee, address operator, address managedGrantContract, TokenGrant tokenGrant ) internal view returns (bool) { require( ManagedGrant(managedGrantContract).grantee() == grantee, "Not a grantee of the provided contract" ); address[] memory operators = tokenGrant.getGranteeOperators( managedGrantContract ); return operators.contains(operator); } /// @notice Returns true if grant with the given ID has been created with /// managed grant pointing currently to the grantee passed as a parameter. /// @dev The function does not revert if grant has not been created with /// a managed grantee. This function is not a view because it uses low-level /// call to check if the grant has been created with a managed grant. /// It does not however modify any state. function isManagedGranteeForGrant( address grantee, uint256 grantId, TokenGrant tokenGrant ) internal returns (bool) { (,,,,, address managedGrant) = tokenGrant.getGrant(grantId); (, bytes memory result) = managedGrant.call( abi.encodeWithSignature("grantee()") ); if (result.length == 0) { return false; } address managedGrantee = abi.decode(result, (address)); return grantee == managedGrantee; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/staking/LockUtils.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; library LockUtils { struct Lock { address creator; uint96 expiresAt; } /// @notice The LockSet is like an array of unique `uint256`s, /// but additionally supports O(1) membership tests and removals. /// @dev Because the LockSet relies on a mapping, /// it can only be used in storage, not in memory. struct LockSet { // locks[positions[lock.creator] - 1] = lock Lock[] locks; mapping(address => uint256) positions; } /// @notice Check whether the LockSet `self` contains a lock by `creator` function contains(LockSet storage self, address creator) internal view returns (bool) { return (self.positions[creator] != 0); } function getLockTime(LockSet storage self, address creator) internal view returns (uint96) { uint256 positionPlusOne = self.positions[creator]; if (positionPlusOne == 0) { return 0; } return self.locks[positionPlusOne - 1].expiresAt; } /// @notice Set the lock of `creator` to `expiresAt`, /// overriding the current value if any. function setLock( LockSet storage self, address _creator, uint96 _expiresAt ) internal { uint256 positionPlusOne = self.positions[_creator]; Lock memory lock = Lock(_creator, _expiresAt); // No existing lock if (positionPlusOne == 0) { self.locks.push(lock); self.positions[_creator] = self.locks.length; // Existing lock present } else { self.locks[positionPlusOne - 1].expiresAt = _expiresAt; } } /// @notice Remove the lock of `creator`. /// If no lock present, do nothing. function releaseLock( LockSet storage self, address _creator ) internal { uint256 positionPlusOne = self.positions[_creator]; if (positionPlusOne != 0) { uint256 lockCount = self.locks.length; if (positionPlusOne != lockCount) { // Not the last lock, // so we need to move the last lock into the emptied position. Lock memory lastLock = self.locks[lockCount - 1]; self.locks[positionPlusOne - 1] = lastLock; self.positions[lastLock.creator] = positionPlusOne; } self.locks.length--; self.positions[_creator] = 0; } } /// @notice Return the locks of the LockSet `self`. function enumerate(LockSet storage self) internal view returns (Lock[] memory) { return self.locks; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/StakeDelegatable.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./utils/OperatorParams.sol"; /// @title Stake Delegatable /// @notice A base contract to allow stake delegation for staking contracts. contract StakeDelegatable { using OperatorParams for uint256; mapping(address => Operator) internal operators; struct Operator { uint256 packedParams; address owner; address payable beneficiary; address authorizer; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function balanceOf(address _address) public view returns (uint256 balance) { return operators[_address].packedParams.getAmount(); } /// @notice Gets the stake owner for the specified operator address. /// @return Stake owner address. function ownerOf(address _operator) public view returns (address) { return operators[_operator].owner; } /// @notice Gets the beneficiary for the specified operator address. /// @return Beneficiary address. function beneficiaryOf(address _operator) public view returns (address payable) { return operators[_operator].beneficiary; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address) { return operators[_operator].authorizer; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/staking/MinimumStakeSchedule.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @notice MinimumStakeSchedule defines the minimum stake parametrization and /// schedule. It starts with a minimum stake of 100k KEEP. Over the following /// 2 years, the minimum stake is lowered periodically using a uniform stepwise /// function, eventually ending at 10k. library MinimumStakeSchedule { using SafeMath for uint256; // 2 years in seconds (seconds per day * days in a year * years) uint256 public constant schedule = 86400 * 365 * 2; uint256 public constant steps = 10; uint256 public constant base = 10000 * 1e18; /// @notice Returns the current value of the minimum stake. The minimum /// stake is lowered periodically over the course of 2 years since the time /// of the shedule start and eventually ends at 10k KEEP. function current(uint256 scheduleStart) internal view returns (uint256) { if (now < scheduleStart.add(schedule)) { uint256 currentStep = steps.mul(now.sub(scheduleStart)).div(schedule); return base.mul(steps.sub(currentStep)); } return base; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/staking/GrantStaking.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "../../TokenGrant.sol"; import "../../TokenStakingEscrow.sol"; import "../..//utils/BytesLib.sol"; import "../RolesLookup.sol"; /// @notice TokenStaking contract library allowing to capture the details of /// delegated grants and offering functions allowing to check grantee /// authentication for stake delegation management. library GrantStaking { using BytesLib for bytes; using RolesLookup for address payable; /// @dev Grant ID is flagged with the most significant bit set, to /// distinguish the grant ID `0` from default (null) value. The flag is /// toggled with bitwise XOR (`^`) which keeps all other bits intact but /// flips the flag bit. The flag should be set before writing to /// `operatorToGrant`, and unset after reading from `operatorToGrant` /// before using the value. uint256 constant GRANT_ID_FLAG = 1 << 255; struct Storage { /// @dev Do not read or write this mapping directly; please use /// `hasGrantDelegated`, `setGrantForOperator`, and `getGrantForOperator` /// instead. mapping (address => uint256) _operatorToGrant; } /// @notice Tries to capture delegation data if the pending delegation has /// been created from a grant. There are only two possibilities and they /// need to be handled differently: delegation comes from the TokenGrant /// contract or delegation comes from TokenStakingEscrow. In those two cases /// grant ID has to be captured in a different way. /// @dev In case of a delegation from the escrow, it is expected that grant /// ID is passed in extraData bytes array. When the delegation comes from /// the TokenGrant contract, delegation data are obtained directly from that /// contract using `tryCapturingGrantId` function. /// @param tokenGrant KEEP token grant contract reference. /// @param escrow TokenStakingEscrow contract address. /// @param from The owner of the tokens who approved them to transfer. /// @param operator The operator tokens are delegated to. /// @param extraData Data for stake delegation, as passed to /// `receiveApproval` of `TokenStaking`. function tryCapturingDelegationData( Storage storage self, TokenGrant tokenGrant, address escrow, address from, address operator, bytes memory extraData ) public returns (bool, uint256) { if (from == escrow) { require(extraData.length == 92, "Corrupted delegation data from escrow"); uint256 grantId = extraData.toUint(60); setGrantForOperator(self, operator, grantId); return (true, grantId); } else { return tryCapturingGrantId(self, tokenGrant, operator); } } /// @notice Checks if the delegation for the given operator has been created /// from a grant defined in the passed token grant contract and if so, /// captures the grant ID for that delegation. /// Grant ID can be later retrieved based on the operator address and used /// to authenticate grantee or to fetch the information about grant /// unlocking schedule for escrow. /// @param tokenGrant KEEP token grant contract reference. /// @param operator The operator tokens are delegated to. function tryCapturingGrantId( Storage storage self, TokenGrant tokenGrant, address operator ) internal returns (bool, uint256) { (bool success, bytes memory data) = address(tokenGrant).call( abi.encodeWithSignature("getGrantStakeDetails(address)", operator) ); if (success) { (uint256 grantId,,address grantStakingContract) = abi.decode( data, (uint256, uint256, address) ); // Double-check if the delegation in TokenGrant has been defined // for this staking contract. If not, it means it's an old // delegation and the current one does not come from a grant. // The scenario covered here is: // - grantee delegated to operator A from a TokenGrant using another // staking contract, // - someone delegates to operator A using liquid tokens and this // staking contract. // Without this check, we'd consider the second delegation as coming // from a grant. if (address(this) != grantStakingContract) { return (false, 0); } setGrantForOperator(self, operator, grantId); return (true, grantId); } return (false, 0); } /// @notice Returns true if the given operator operates on stake delegated /// from a grant. false is returned otherwise. /// @param operator The operator to which tokens from a grant are /// potentially delegated to. function hasGrantDelegated( Storage storage self, address operator ) public view returns (bool) { return self._operatorToGrant[operator] != 0; } /// @notice Associates operator with the provided grant ID. It means that /// the given operator delegates on stake from the grant with this ID. /// @param operator The operator tokens are delegate to. /// @param grantId Identifier of a grant from which the tokens are delegated /// to. function setGrantForOperator( Storage storage self, address operator, uint256 grantId ) public { self._operatorToGrant[operator] = grantId ^ GRANT_ID_FLAG; } /// @notice Returns grant ID for the provided operator. If the operator /// does not operate on stake delegated from a grant, function reverts. /// @dev To avoid reverting in case the grant ID for the operator does not /// exist, consider calling hasGrantDelegated before. /// @param operator The operator tokens are delegate to. function getGrantForOperator( Storage storage self, address operator ) public view returns (uint256) { uint256 grantId = self._operatorToGrant[operator]; require (grantId != 0, "No grant for the operator"); return grantId ^ GRANT_ID_FLAG; } /// @notice Returns true if msg.sender is grantee eligible to trigger stake /// undelegation for this operator. Function checks both standard grantee /// and managed grantee case. /// @param operator The operator tokens are delegated to. /// @param tokenGrant KEEP token grant contract reference. function canUndelegate( Storage storage self, address operator, TokenGrant tokenGrant ) public returns (bool) { // First of all, we need to see if the operator has grant delegated. // If not, we don't need to bother about checking grantee or // managed grantee and we just return false. if (!hasGrantDelegated(self, operator)) { return false; } uint256 grantId = getGrantForOperator(self, operator); (,,,,uint256 revokedAt, address grantee) = tokenGrant.getGrant(grantId); // Is msg.sender grantee of a standard grant? if (msg.sender == grantee) { return true; } // If not, we need to dig deeper and see if we are dealing with // a grantee from a managed grant. if ((msg.sender).isManagedGranteeForGrant(grantId, tokenGrant)) { return true; } // There is only one possibility left - grant has been revoked and // grant manager wants to take back delegated tokens. if (revokedAt == 0) { return false; } (address grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); return msg.sender == grantManager; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/TokenGrant.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./utils/AddressArrayUtils.sol"; import "./TokenStaking.sol"; import "./TokenGrantStake.sol"; import "./GrantStakingPolicy.sol"; /// @title TokenGrant /// @notice A token grant contract for a specified standard ERC20Burnable token. /// Has additional functionality to stake delegate/undelegate token grants. /// Tokens are granted to the grantee via unlocking scheme and can be /// withdrawn gradually based on the unlocking schedule cliff and unlocking duration. /// Optionally grant can be revoked by the token grant manager. contract TokenGrant { using SafeMath for uint256; using UnlockingSchedule for uint256; using SafeERC20 for ERC20Burnable; using BytesLib for bytes; using AddressArrayUtils for address[]; event TokenGrantCreated(uint256 id); event TokenGrantWithdrawn(uint256 indexed grantId, uint256 amount); event TokenGrantStaked(uint256 indexed grantId, uint256 amount, address operator); event TokenGrantRevoked(uint256 id); event StakingContractAuthorized(address indexed grantManager, address stakingContract); struct Grant { address grantManager; // Token grant manager. address grantee; // Address to which granted tokens are going to be withdrawn. uint256 revokedAt; // Timestamp at which grant was revoked by the grant manager. uint256 revokedAmount; // The number of tokens revoked from the grantee. uint256 revokedWithdrawn; // The number of tokens returned to the grant creator. bool revocable; // Whether grant manager can revoke the grant. uint256 amount; // Amount of tokens to be granted. uint256 duration; // Duration in seconds of the period in which the granted tokens will unlock. uint256 start; // Timestamp at which the linear unlocking schedule will start. uint256 cliff; // Timestamp before which no tokens will be unlocked. uint256 withdrawn; // Amount that was withdrawn to the grantee. uint256 staked; // Amount that was staked by the grantee. GrantStakingPolicy stakingPolicy; } uint256 public numGrants; ERC20Burnable public token; // Staking contracts authorized by the given grant manager. // grant manager -> staking contract -> authorized? mapping(address => mapping (address => bool)) internal stakingContracts; // Token grants. mapping(uint256 => Grant) public grants; // Token grants stakes. mapping(address => TokenGrantStake) public grantStakes; // Mapping of token grant IDs per particular address // involved in a grant as a grantee or as a grant manager. mapping(address => uint256[]) public grantIndices; // Token grants balances. Sum of all granted tokens to a grantee. // This includes granted tokens that are already unlocked and // available to be withdrawn to the grantee mapping(address => uint256) public balances; // Mapping of operator addresses per particular grantee address. mapping(address => address[]) public granteesToOperators; /// @notice Creates a token grant contract for a provided Standard ERC20Burnable token. /// @param _tokenAddress address of a token that will be linked to this contract. constructor(address _tokenAddress) public { require(_tokenAddress != address(0x0), "Token address can't be zero."); token = ERC20Burnable(_tokenAddress); } /// @notice Used by grant manager to authorize staking contract with the given /// address. function authorizeStakingContract(address _stakingContract) public { require( _stakingContract != address(0x0), "Staking contract address can't be zero" ); stakingContracts[msg.sender][_stakingContract] = true; emit StakingContractAuthorized(msg.sender, _stakingContract); } /// @notice Gets the amount of granted tokens to the specified address. /// @param _owner The address to query the grants balance of. /// @return An uint256 representing the grants balance owned by the passed address. function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function stakeBalanceOf(address _address) public view returns (uint256 balance) { for (uint i = 0; i < grantIndices[_address].length; i++) { uint256 id = grantIndices[_address][i]; balance += grants[id].staked; } return balance; } /// @notice Gets grant by ID. Returns only basic grant data. /// If you need unlocking schedule for the grant you must call `getGrantUnlockingSchedule()` /// This is to avoid Ethereum `Stack too deep` issue described here: /// https://forum.ethereum.org/discussion/2400/error-stack-too-deep-try-removing-local-variables /// @param _id ID of the token grant. /// @return amount The amount of tokens the grant provides. /// @return withdrawn The amount of tokens that have already been withdrawn /// from the grant. /// @return staked The amount of tokens that have been staked from the grant. /// @return revoked A boolean indicating whether the grant has been revoked, /// which is to say that it is no longer unlocking. /// @return grantee The grantee of grant. function getGrant(uint256 _id) public view returns ( uint256 amount, uint256 withdrawn, uint256 staked, uint256 revokedAmount, uint256 revokedAt, address grantee ) { return ( grants[_id].amount, grants[_id].withdrawn, grants[_id].staked, grants[_id].revokedAmount, grants[_id].revokedAt, grants[_id].grantee ); } /// @notice Gets grant unlocking schedule by grant ID. /// @param _id ID of the token grant. /// @return grantManager The address designated as the manager of the grant, /// which is the only address that can revoke this grant. /// @return duration The duration, in seconds, during which the tokens will /// unlocking linearly. /// @return start The start time, as a timestamp comparing to `now`. /// @return cliff The timestamp, before which none of the tokens in the grant /// will be unlocked, and after which a linear amount based on /// the time elapsed since the start will be unlocked. /// @return policy The address of the grant's staking policy. function getGrantUnlockingSchedule( uint256 _id ) public view returns ( address grantManager, uint256 duration, uint256 start, uint256 cliff, address policy ) { return ( grants[_id].grantManager, grants[_id].duration, grants[_id].start, grants[_id].cliff, address(grants[_id].stakingPolicy) ); } /// @notice Gets grant ids of the specified address. /// @param _granteeOrGrantManager The address to query. /// @return An uint256 array of grant IDs. function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) { return grantIndices[_granteeOrGrantManager]; } /// @notice Gets operator addresses of the specified grantee address. /// @param grantee The grantee address. /// @return An array of all operators for a given grantee. function getGranteeOperators(address grantee) public view returns (address[] memory) { return granteesToOperators[grantee]; } /// @notice Gets grant stake details of the given operator. /// @param operator The operator address. /// @return grantId ID of the token grant. /// @return amount The amount of tokens the given operator delegated. /// @return stakingContract The address of staking contract. function getGrantStakeDetails(address operator) public view returns (uint256 grantId, uint256 amount, address stakingContract) { return grantStakes[operator].getDetails(); } /// @notice Receives approval of token transfer and creates a token grant with a unlocking /// schedule where balance withdrawn to the grantee gradually in a linear fashion until /// start + duration. By then all of the balance will have unlocked. /// @param _from The owner of the tokens who approved them to transfer. /// @param _amount Approved amount for the transfer to create token grant. /// @param _token Token contract address. /// @param _extraData This byte array must have the following values ABI encoded: /// grantManager (address) Address of the grant manager. /// grantee (address) Address of the grantee. /// duration (uint256) Duration in seconds of the unlocking period. /// start (uint256) Timestamp at which unlocking will start. /// cliffDuration (uint256) Duration in seconds of the cliff; /// no tokens will be unlocked until the time `start + cliff`. /// revocable (bool) Whether the token grant is revocable or not (1 or 0). /// stakingPolicy (address) Address of the staking policy for the grant. function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _extraData) public { require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract."); require(_amount <= token.balanceOf(_from), "Sender must have enough amount."); (address _grantManager, address _grantee, uint256 _duration, uint256 _start, uint256 _cliffDuration, bool _revocable, address _stakingPolicy) = abi.decode( _extraData, (address, address, uint256, uint256, uint256, bool, address) ); require(_grantee != address(0), "Grantee address can't be zero."); require( _cliffDuration <= _duration, "Unlocking cliff duration must be less or equal total unlocking duration." ); require(_stakingPolicy != address(0), "Staking policy can't be zero."); uint256 id = numGrants++; grants[id] = Grant( _grantManager, _grantee, 0, 0, 0, _revocable, _amount, _duration, _start, _start.add(_cliffDuration), 0, 0, GrantStakingPolicy(_stakingPolicy) ); // Maintain a record to make it easier to query grants by grant manager. grantIndices[_from].push(id); // Maintain a record to make it easier to query grants by grantee. grantIndices[_grantee].push(id); token.safeTransferFrom(_from, address(this), _amount); // Maintain a record of the unlocked amount balances[_grantee] = balances[_grantee].add(_amount); emit TokenGrantCreated(id); } /// @notice Withdraws Token grant amount to grantee. /// @dev Transfers unlocked tokens of the token grant to grantee. /// @param _id Grant ID. function withdraw(uint256 _id) public { uint256 amount = withdrawable(_id); require(amount > 0, "Grant available to withdraw amount should be greater than zero."); // Update withdrawn amount. grants[_id].withdrawn = grants[_id].withdrawn.add(amount); // Update grantee grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(amount); // Transfer tokens from this contract balance to the grantee token balance. token.safeTransfer(grants[_id].grantee, amount); emit TokenGrantWithdrawn(_id, amount); } /// @notice Calculates and returns unlocked grant amount. /// @dev Calculates token grant amount that has already unlocked, /// including any tokens that have already been withdrawn by the grantee as well /// as any tokens that are available to withdraw but have not yet been withdrawn. /// @param _id Grant ID. function unlockedAmount(uint256 _id) public view returns (uint256) { Grant storage grant = grants[_id]; return (grant.revokedAt != 0) // Grant revoked -> return what is remaining ? grant.amount.sub(grant.revokedAmount) // Not revoked -> calculate the unlocked amount normally : now.getUnlockedAmount( grant.amount, grant.duration, grant.start, grant.cliff ); } /// @notice Calculates withdrawable granted amount. /// @dev Calculates the amount that has already unlocked but hasn't been withdrawn yet. /// @param _id Grant ID. function withdrawable(uint256 _id) public view returns (uint256) { uint256 unlocked = unlockedAmount(_id); uint256 withdrawn = grants[_id].withdrawn; uint256 staked = grants[_id].staked; if (withdrawn.add(staked) >= unlocked) { return 0; } else { return unlocked.sub(withdrawn).sub(staked); } } /// @notice Allows the grant manager to revoke the grant. /// @dev Granted tokens that are already unlocked (releasable amount) /// remain in the grant so grantee can still withdraw them /// the rest are revoked and withdrawable by token grant manager. /// @param _id Grant ID. function revoke(uint256 _id) public { require(grants[_id].grantManager == msg.sender, "Only grant manager can revoke."); require(grants[_id].revocable, "Grant must be revocable in the first place."); require(grants[_id].revokedAt == 0, "Grant must not be already revoked."); uint256 unlockedAmount = unlockedAmount(_id); uint256 revokedAmount = grants[_id].amount.sub(unlockedAmount); grants[_id].revokedAt = now; grants[_id].revokedAmount = revokedAmount; // Update grantee's grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(revokedAmount); emit TokenGrantRevoked(_id); } /// @notice Allows the grant manager to withdraw revoked tokens. /// @dev Will withdraw as many of the revoked tokens as possible /// without pushing the grant contract into a token deficit. /// If the grantee has staked more tokens than the unlocked amount, /// those tokens will remain in the grant until undelegated and returned, /// after which they can be withdrawn by calling `withdrawRevoked` again. /// @param _id Grant ID. function withdrawRevoked(uint256 _id) public { Grant storage grant = grants[_id]; require( grant.grantManager == msg.sender, "Only grant manager can withdraw revoked tokens." ); uint256 revoked = grant.revokedAmount; uint256 revokedWithdrawn = grant.revokedWithdrawn; require(revokedWithdrawn < revoked, "All revoked tokens withdrawn."); uint256 revokedRemaining = revoked.sub(revokedWithdrawn); uint256 totalAmount = grant.amount; uint256 staked = grant.staked; uint256 granteeWithdrawn = grant.withdrawn; uint256 remainingPresentInGrant = totalAmount.sub(staked).sub(revokedWithdrawn).sub(granteeWithdrawn); require(remainingPresentInGrant > 0, "No revoked tokens withdrawable."); uint256 amountToWithdraw = remainingPresentInGrant < revokedRemaining ? remainingPresentInGrant : revokedRemaining; token.safeTransfer(msg.sender, amountToWithdraw); grant.revokedWithdrawn += amountToWithdraw; } /// @notice Stake token grant. /// @dev Stakable token grant amount is determined /// by the grant's staking policy. /// @param _id Grant Id. /// @param _stakingContract Address of the staking contract. /// @param _amount Amount to stake. /// @param _extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function stake(uint256 _id, address _stakingContract, uint256 _amount, bytes memory _extraData) public { require(grants[_id].grantee == msg.sender, "Only grantee of the grant can stake it."); require(grants[_id].revokedAt == 0, "Revoked grant can not be staked"); require( stakingContracts[grants[_id].grantManager][_stakingContract], "Provided staking contract is not authorized." ); // Expecting 60 bytes _extraData for stake delegation. require(_extraData.length == 60, "Stake delegation data must be provided."); address operator = _extraData.toAddress(20); // Calculate available amount. Amount of unlocked tokens minus what user already withdrawn and staked. require(_amount <= availableToStake(_id), "Must have available granted amount to stake."); // Keep staking record. TokenGrantStake grantStake = new TokenGrantStake( address(token), _id, _stakingContract ); grantStakes[operator] = grantStake; granteesToOperators[grants[_id].grantee].push(operator); grants[_id].staked += _amount; token.transfer(address(grantStake), _amount); // Staking contract expects 40 bytes _extraData for stake delegation. // 20 bytes beneficiary's address + 20 bytes operator's address. grantStake.stake(_amount, _extraData); emit TokenGrantStaked(_id, _amount, operator); } /// @notice Returns the amount of tokens available for staking from the grant. /// The stakeable amount is determined by the staking policy of the grant. /// If the grantee has withdrawn some tokens /// or the policy returns an erroneously high value, /// the stakeable amount is limited to the number of tokens remaining. /// @param _grantId Identifier of the grant function availableToStake(uint256 _grantId) public view returns (uint256) { Grant storage grant = grants[_grantId]; // Revoked grants cannot be staked. // If the grant isn't revoked, the number of revoked tokens is 0. if (grant.revokedAt != 0) { return 0; } uint256 amount = grant.amount; uint256 withdrawn = grant.withdrawn; uint256 remaining = amount.sub(withdrawn); uint256 stakeable = grant.stakingPolicy.getStakeableAmount( now, amount, grant.duration, grant.start, grant.cliff, withdrawn ); // Clamp the stakeable amount to what is left in the grant // in the case of a malfunctioning staking policy. if (stakeable > remaining) { stakeable = remaining; } return stakeable.sub(grant.staked); } /// @notice Cancels delegation within the operator initialization period /// without being subjected to the stake lockup for the undelegation period. /// This can be used to undo mistaken delegation to the wrong operator address. /// @param _operator Address of the stake operator. function cancelStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can cancel the delegation." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Undelegate the token grant. /// @param _operator Operator of the stake. function undelegate(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can undelegate." ); grantStake.undelegate(); } /// @notice Force cancellation of a revoked grant's stake. /// Can be used by the grant manager /// to immediately withdraw tokens back into the grant, /// from an operator still within the initialization period. /// These tokens can then be withdrawn /// if some revoked tokens haven't been withdrawn yet. function cancelRevokedStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force cancellation of revoked grant stake." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Force undelegation of a revoked grant's stake. /// @dev Can be called by the grant manager once the grant is revoked. /// Has to be done this way, instead of undelegating all operators when the /// grant is revoked, because the latter method is vulnerable to DoS via /// out-of-gas. function undelegateRevoked(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force undelegation of revoked grant stake" ); grantStake.undelegate(); } /// @notice Recover stake of the token grant. /// Recovers the tokens correctly /// even if they were earlier recovered directly in the staking contract. /// @param _operator Operator of the stake. function recoverStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 returned = grantStake.recoverStake(); uint256 grantId = grantStake.getGrantId(); grants[grantId].staked = grants[grantId].staked.sub(returned); delete grantStakes[_operator]; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/staking/Locks.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { AuthorityVerifier } from "../../Authorizations.sol"; import "./LockUtils.sol"; library Locks { using SafeMath for uint256; using LockUtils for LockUtils.LockSet; event StakeLocked(address indexed operator, address lockCreator, uint256 until); event LockReleased(address indexed operator, address lockCreator); event ExpiredLockReleased(address indexed operator, address lockCreator); uint256 public constant maximumLockDuration = 86400 * 200; // 200 days in seconds struct Storage { // Locks placed on the operator. // `operatorLocks[operator]` returns all locks placed on the operator. // Each authorized operator contract can place one lock on an operator. mapping(address => LockUtils.LockSet) operatorLocks; } function lockStake( Storage storage self, address operator, uint256 duration ) public { require(duration <= maximumLockDuration, "Lock duration too long"); self.operatorLocks[operator].setLock( msg.sender, uint96(block.timestamp.add(duration)) ); emit StakeLocked(operator, msg.sender, block.timestamp.add(duration)); } function releaseLock( Storage storage self, address operator ) public { self.operatorLocks[operator].releaseLock(msg.sender); emit LockReleased(operator, msg.sender); } function releaseExpiredLock( Storage storage self, address operator, address operatorContract, address authorityVerifier ) public { LockUtils.LockSet storage locks = self.operatorLocks[operator]; require( locks.contains(operatorContract), "No matching lock present" ); bool expired = block.timestamp >= locks.getLockTime(operatorContract); bool disabled = !AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(operatorContract); require( expired || disabled, "Lock still active and valid" ); locks.releaseLock(operatorContract); emit ExpiredLockReleased(operator, operatorContract); } /// @dev AuthorityVerifier is a trusted implementation and not a third-party, /// external contract. AuthorityVerifier never reverts on the check and /// has a reasonable gas consumption. function isStakeLocked( Storage storage self, address operator, address authorityVerifier ) public view returns (bool) { LockUtils.Lock[] storage _locks = self.operatorLocks[operator].locks; LockUtils.Lock memory lock; for (uint i = 0; i < _locks.length; i++) { lock = _locks[i]; if (block.timestamp < lock.expiresAt) { if ( AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(lock.creator) ) { return true; } } } return false; } function isStakeReleased( Storage storage self, address operator, address operatorContract ) public view returns (bool) { LockUtils.LockSet storage locks = self.operatorLocks[operator]; // `getLockTime` returns 0 if the lock doesn't exist, // thus we don't need to check for its presence separately. return block.timestamp >= locks.getLockTime(operatorContract); } function getLocks( Storage storage self, address operator ) public view returns (address[] memory creators, uint256[] memory expirations) { uint256 lockCount = self.operatorLocks[operator].locks.length; creators = new address[](lockCount); expirations = new uint256[](lockCount); LockUtils.Lock memory lock; for (uint i = 0; i < lockCount; i++) { lock = self.operatorLocks[operator].locks[i]; creators[i] = lock.creator; expirations[i] = lock.expiresAt; } } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/libraries/staking/TopUps.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../TokenStakingEscrow.sol"; import "../../utils/OperatorParams.sol"; /// @notice TokenStaking contract library allowing to perform two-step stake /// top-ups for existing delegations. /// Top-up is a two-step process: it is initiated with a declared top-up value /// and after waiting for at least the initialization period it can be /// committed. library TopUps { using SafeMath for uint256; using OperatorParams for uint256; event TopUpInitiated(address indexed operator, uint256 topUp); event TopUpCompleted(address indexed operator, uint256 newAmount); struct TopUp { uint256 amount; uint256 createdAt; } struct Storage { // operator -> TopUp mapping(address => TopUp) topUps; } /// @notice Performs top-up in one step when stake is not yet initialized by /// adding the top-up amount to the stake and resetting stake initialization /// time counter. /// @dev This function should be called only for not yet initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. /// @return New value of parameters. It should be updated for the operator /// in the staking contract. function instantComplete( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public returns (uint256 newParams) { // Stake is not yet initialized so we don't need to check if the // operator is not undelegating - initializing and undelegating at the // same time is not possible. We do however, need to check whether the // operator has not canceled its previous stake for that operator, // depositing the stake it in the escrow. We do not want to allow // resurrecting operators with cancelled stake by top-ups. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); uint256 newAmount = operatorParams.getAmount().add(value); newParams = operatorParams.setAmountAndCreationTimestamp( newAmount, block.timestamp ); emit TopUpCompleted(operator, newAmount); } /// @notice Initiates top-up of the given value for tokens delegated to /// the provided operator. If there is an existing top-up still /// initializing, top-up values are summed up and initialization period /// is set to the current block timestamp. /// @dev This function should be called only for active operators with /// initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. function initiate( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public { // Stake is initialized, the operator is still active so we need // to check if it's not undelegating. require(!isUndelegating(operatorParams), "Stake undelegated"); // We also need to check if the stake for the operator is not already // in the escrow because it's been previously cancelled. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); TopUp memory awaiting = self.topUps[operator]; self.topUps[operator] = TopUp(awaiting.amount.add(value), now); emit TopUpInitiated(operator, value); } /// @notice Commits the top-up if it passed the initialization period. /// Tokens are added to the stake once the top-up is committed. /// @param operator Operator The operator with a pending stake top-up. /// @param initializationPeriod Stake initialization period. function commit( Storage storage self, address operator, uint256 operatorParams, uint256 initializationPeriod ) public returns (uint256 newParams) { TopUp memory topUp = self.topUps[operator]; require(topUp.amount > 0, "No top up to commit"); require( now > topUp.createdAt.add(initializationPeriod), "Stake is initializing" ); uint256 newAmount = operatorParams.getAmount().add(topUp.amount); newParams = operatorParams.setAmount(newAmount); delete self.topUps[operator]; emit TopUpCompleted(operator, newAmount); } /// @notice Cancels pending, initiating top-up. If there is no initiating /// top-up for the operator, function does nothing. This function should be /// used when the stake is recovered to return tokens from a pending, /// initiating top-up. /// @param operator Operator The operator from which the stake is recovered. function cancel( Storage storage self, address operator ) public returns (uint256) { TopUp memory topUp = self.topUps[operator]; if (topUp.amount == 0) { return 0; } delete self.topUps[operator]; return topUp.amount; } /// @notice Returns true if the given operatorParams indicate that the /// operator is undelegating its stake or that it completed stake /// undelegation. /// @param operatorParams Parameters of the operator, as stored in the /// staking contract. function isUndelegating(uint256 operatorParams) internal view returns (bool) { uint256 undelegatedAt = operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
@keep-network/keep-core/contracts/utils/PercentUtils.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library PercentUtils { using SafeMath for uint256; // Return `b`% of `a` // 200.percent(40) == 80 // Commutative, works both ways function percent(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(100); } // Return `a` as percentage of `b`: // 80.asPercentOf(200) == 40 function asPercentOf(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(100).div(b); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
openzeppelin-solidity/contracts/math/SafeMath.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ 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, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/KeepBonding.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./AbstractBonding.sol"; import "@keep-network/keep-core/contracts/TokenGrant.sol"; import "@keep-network/keep-core/contracts/libraries/RolesLookup.sol"; /// @title Keep Bonding /// @notice Contract holding deposits from keeps' operators. contract KeepBonding is AbstractBonding { using RolesLookup for address payable; // KEEP Token Staking contract. TokenStaking internal tokenStaking; // KEEP token grant contract. TokenGrant internal tokenGrant; /// @notice Initializes Keep Bonding contract. /// @param registryAddress Keep registry contract address. /// @param tokenStakingAddress KEEP token staking contract address. /// @param tokenGrantAddress KEEP token grant contract address. constructor( address registryAddress, address tokenStakingAddress, address tokenGrantAddress ) public AbstractBonding(registryAddress) { tokenStaking = TokenStaking(tokenStakingAddress); tokenGrant = TokenGrant(tokenGrantAddress); } /// @notice Withdraws amount from operator's value available for bonding. /// Should not be used by grantee of managed grants. For this case, /// please use `withdrawAsManagedGrantee`. /// /// This function can be called only by: /// - operator, /// - liquid, staked tokens owner (not a grant), /// - direct staked tokens grantee (not a managed grant). /// /// @param amount Value to withdraw in wei. /// @param operator Address of the operator. function withdraw(uint256 amount, address operator) public { require( msg.sender == operator || msg.sender.isTokenOwnerForOperator(operator, tokenStaking) || msg.sender.isGranteeForOperator(operator, tokenGrant), "Only operator or the owner is allowed to withdraw bond" ); withdrawBond(amount, operator); } /// @notice Withdraws amount from operator's value available for bonding. /// Can be called only by staked tokens managed grantee. /// @param amount Value to withdraw in wei. /// @param operator Address of the operator. /// @param managedGrant Address of the managed grant contract. function withdrawAsManagedGrantee( uint256 amount, address operator, address managedGrant ) public { require( msg.sender.isManagedGranteeForOperator( operator, managedGrant, tokenGrant ), "Only grantee is allowed to withdraw bond" ); withdrawBond(amount, operator); } function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool) { return tokenStaking.isAuthorizedForOperator(_operator, _operatorContract); } function authorizerOf(address _operator) public view returns (address) { return tokenStaking.authorizerOf(_operator); } function beneficiaryOf(address _operator) public view returns (address payable) { return tokenStaking.beneficiaryOf(_operator); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
BondedECDSAKeep
solidity/contracts/AbstractBonding.sol
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
Solidity
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./api/IBondingManagement.sol"; import "@keep-network/keep-core/contracts/KeepRegistry.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @title Abstract Bonding /// @notice Contract holding deposits from keeps' operators. contract AbstractBonding is IBondingManagement { using SafeMath for uint256; // Registry contract with a list of approved factories (operator contracts). KeepRegistry internal registry; // Unassigned value in wei deposited by operators. mapping(address => uint256) public unbondedValue; // References to created bonds. Bond identifier is built from operator's // address, holder's address and reference ID assigned on bond creation. mapping(bytes32 => uint256) internal lockedBonds; // Sortition pools authorized by operator's authorizer. // operator -> pool -> boolean mapping(address => mapping(address => bool)) internal authorizedPools; event UnbondedValueDeposited( address indexed operator, address indexed beneficiary, uint256 amount ); event UnbondedValueWithdrawn( address indexed operator, address indexed beneficiary, uint256 amount ); event BondCreated( address indexed operator, address indexed holder, address indexed sortitionPool, uint256 referenceID, uint256 amount ); event BondReassigned( address indexed operator, uint256 indexed referenceID, address newHolder, uint256 newReferenceID ); event BondReleased(address indexed operator, uint256 indexed referenceID); event BondSeized( address indexed operator, uint256 indexed referenceID, address destination, uint256 amount ); /// @notice Initializes Keep Bonding contract. /// @param registryAddress Keep registry contract address. constructor(address registryAddress) public { registry = KeepRegistry(registryAddress); } /// @notice Add the provided value to operator's pool available for bonding. /// @param operator Address of the operator. function deposit(address operator) public payable { address beneficiary = beneficiaryOf(operator); // Beneficiary has to be set (delegation exist) before an operator can // deposit wei. It protects from a situation when an operator wants // to withdraw funds which are transfered to beneficiary with zero // address. require( beneficiary != address(0), "Beneficiary not defined for the operator" ); unbondedValue[operator] = unbondedValue[operator].add(msg.value); emit UnbondedValueDeposited(operator, beneficiary, msg.value); } /// @notice Withdraws amount from operator's value available for bonding. /// @param amount Value to withdraw in wei. /// @param operator Address of the operator. function withdraw(uint256 amount, address operator) public; /// @notice Returns the amount of wei the operator has made available for /// bonding and that is still unbounded. If the operator doesn't exist or /// bond creator is not authorized as an operator contract or it is not /// authorized by the operator or there is no secondary authorization for /// the provided sortition pool, function returns 0. /// @dev Implements function expected by sortition pools' IBonding interface. /// @param operator Address of the operator. /// @param bondCreator Address authorized to create a bond. /// @param authorizedSortitionPool Address of authorized sortition pool. /// @return Amount of authorized wei deposit available for bonding. function availableUnbondedValue( address operator, address bondCreator, address authorizedSortitionPool ) public view returns (uint256) { // Sortition pools check this condition and skips operators that // are no longer eligible. We cannot revert here. if ( registry.isApprovedOperatorContract(bondCreator) && isAuthorizedForOperator(operator, bondCreator) && hasSecondaryAuthorization(operator, authorizedSortitionPool) ) { return unbondedValue[operator]; } return 0; } /// @notice Create bond for the given operator, holder, reference and amount. /// @dev Function can be executed only by authorized contract. Reference ID /// should be unique for holder and operator. /// @param operator Address of the operator to bond. /// @param holder Address of the holder of the bond. /// @param referenceID Reference ID used to track the bond by holder. /// @param amount Value to bond in wei. /// @param authorizedSortitionPool Address of authorized sortition pool. function createBond( address operator, address holder, uint256 referenceID, uint256 amount, address authorizedSortitionPool ) public { require( availableUnbondedValue( operator, msg.sender, authorizedSortitionPool ) >= amount, "Insufficient unbonded value" ); bytes32 bondID = keccak256( abi.encodePacked(operator, holder, referenceID) ); require( lockedBonds[bondID] == 0, "Reference ID not unique for holder and operator" ); unbondedValue[operator] = unbondedValue[operator].sub(amount); lockedBonds[bondID] = lockedBonds[bondID].add(amount); emit BondCreated( operator, holder, authorizedSortitionPool, referenceID, amount ); } /// @notice Returns value of wei bonded for the operator. /// @param operator Address of the operator. /// @param holder Address of the holder of the bond. /// @param referenceID Reference ID of the bond. /// @return Amount of wei in the selected bond. function bondAmount( address operator, address holder, uint256 referenceID ) public view returns (uint256) { bytes32 bondID = keccak256( abi.encodePacked(operator, holder, referenceID) ); return lockedBonds[bondID]; } /// @notice Reassigns a bond to a new holder under a new reference. /// @dev Function requires that a caller is the current holder of the bond /// which is being reassigned. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. /// @param newHolder Address of the new holder of the bond. /// @param newReferenceID New reference ID to register the bond. function reassignBond( address operator, uint256 referenceID, address newHolder, uint256 newReferenceID ) public { address holder = msg.sender; bytes32 bondID = keccak256( abi.encodePacked(operator, holder, referenceID) ); require(lockedBonds[bondID] > 0, "Bond not found"); bytes32 newBondID = keccak256( abi.encodePacked(operator, newHolder, newReferenceID) ); require( lockedBonds[newBondID] == 0, "Reference ID not unique for holder and operator" ); lockedBonds[newBondID] = lockedBonds[bondID]; lockedBonds[bondID] = 0; emit BondReassigned(operator, referenceID, newHolder, newReferenceID); } /// @notice Releases the bond and moves the bond value to the operator's /// unbounded value pool. /// @dev Function requires that caller is the holder of the bond which is /// being released. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. function freeBond(address operator, uint256 referenceID) public { address holder = msg.sender; bytes32 bondID = keccak256( abi.encodePacked(operator, holder, referenceID) ); require(lockedBonds[bondID] > 0, "Bond not found"); uint256 amount = lockedBonds[bondID]; lockedBonds[bondID] = 0; unbondedValue[operator] = unbondedValue[operator].add(amount); emit BondReleased(operator, referenceID); } /// @notice Seizes the bond by moving some or all of the locked bond to the /// provided destination address. /// @dev Function requires that a caller is the holder of the bond which is /// being seized. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. /// @param amount Amount to be seized. /// @param destination Address to send the amount to. function seizeBond( address operator, uint256 referenceID, uint256 amount, address payable destination ) public { require(amount > 0, "Requested amount should be greater than zero"); address payable holder = msg.sender; bytes32 bondID = keccak256( abi.encodePacked(operator, holder, referenceID) ); require( lockedBonds[bondID] >= amount, "Requested amount is greater than the bond" ); lockedBonds[bondID] = lockedBonds[bondID].sub(amount); (bool success, ) = destination.call.value(amount)(""); require(success, "Transfer failed"); emit BondSeized(operator, referenceID, destination, amount); } /// @notice Authorizes sortition pool for the provided operator. /// Operator's authorizers need to authorize individual sortition pools /// per application since they may be interested in participating only in /// a subset of keep types used by the given application. /// @dev Only operator's authorizer can call this function. function authorizeSortitionPoolContract( address _operator, address _poolAddress ) public { require(authorizerOf(_operator) == msg.sender, "Not authorized"); authorizedPools[_operator][_poolAddress] = true; } /// @notice Deauthorizes sortition pool for the provided operator. /// Authorizer may deauthorize individual sortition pool in case the /// operator should no longer be eligible for work selection and the /// application represented by the sortition pool should no longer be /// eligible to create bonds for the operator. /// @dev Only operator's authorizer can call this function. function deauthorizeSortitionPoolContract( address _operator, address _poolAddress ) public { require(authorizerOf(_operator) == msg.sender, "Not authorized"); authorizedPools[_operator][_poolAddress] = false; } /// @notice Checks if the sortition pool has been authorized for the /// provided operator by its authorizer. /// @dev See authorizeSortitionPoolContract. function hasSecondaryAuthorization(address _operator, address _poolAddress) public view returns (bool) { return authorizedPools[_operator][_poolAddress]; } /// @notice Checks if operator contract has been authorized for the provided /// operator. /// @param _operator Operator address. /// @param _operatorContract Address of the operator contract. function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool); /// @notice Gets the authorizer for the specified operator address. /// @param _operator Operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address); /// @notice Gets the beneficiary for the specified operator address. /// @param _operator Operator address. /// @return Beneficiary address. function beneficiaryOf(address _operator) public view returns (address payable); /// @notice Withdraws the provided amount from unbonded value of the /// provided operator to operator's beneficiary. If there is no enough /// unbonded value or the transfer failed, function fails. function withdrawBond(uint256 amount, address operator) internal { require( unbondedValue[operator] >= amount, "Insufficient unbonded value" ); unbondedValue[operator] = unbondedValue[operator].sub(amount); address beneficiary = beneficiaryOf(operator); (bool success, ) = beneficiary.call.value(amount)(""); require(success, "Transfer failed"); emit UnbondedValueWithdrawn(operator, beneficiary, amount); } }
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
v0.5.17+commit.d19bba13
true
200
Default
MIT
false
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
UpgradeBeaconProxyV1
UpgradeBeaconProxyV1.sol
0x88507f1db8d0f9c54a55b0941b785288b1fa3f16
Solidity
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg /** * @title UpgradeBeaconProxyV1 * @author 0age * @notice This contract delegates all logic, including initialization, to an * implementation contract specified by a hard-coded "upgrade beacon" contract. * Note that this implementation can be reduced in size by stripping out the * metadata hash, or even more significantly by using a minimal upgrade beacon * proxy implemented using raw EVM opcodes. */ contract UpgradeBeaconProxyV1 { // Set upgrade beacon address as a constant (i.e. not in contract storage). address private constant _UPGRADE_BEACON = address( 0x000000000026750c571ce882B17016557279ADaa ); /** * @notice In the constructor, perform initialization via delegatecall to the * implementation set on the upgrade beacon, supplying initialization calldata * as a constructor argument. The deployment will revert and pass along the * revert reason in the event that this initialization delegatecall reverts. * @param initializationCalldata Calldata to supply when performing the * initialization delegatecall. */ constructor(bytes memory initializationCalldata) public payable { // Delegatecall into the implementation, supplying initialization calldata. (bool ok, ) = _implementation().delegatecall(initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } /** * @notice In the fallback, delegate execution to the implementation set on * the upgrade beacon. */ function () external payable { // Delegate execution to implementation contract provided by upgrade beacon. _delegate(_implementation()); } /** * @notice Private view function to get the current implementation from the * upgrade beacon. This is accomplished via a staticcall to the beacon with no * data, and the beacon will return an abi-encoded implementation address. * @return implementation Address of the implementation. */ function _implementation() private view returns (address implementation) { // Get the current implementation address from the upgrade beacon. (bool ok, bytes memory returnData) = _UPGRADE_BEACON.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(ok, string(returnData)); // Set the implementation to the address returned from the upgrade beacon. implementation = abi.decode(returnData, (address)); } /** * @notice Private function that delegates execution to an implementation * contract. This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param implementation Address to delegate. */ function _delegate(address implementation) private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } }
[{"inputs":[{"internalType":"bytes","name":"initializationCalldata","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.5.11+commit.c082d0b4
true
200
00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de80000000000000000000000007e4a8391c728fed9069b2962699ab416628b19fa00000000000000000000000000000000000000000000000000000000
Default
MIT
false
bzzr://20202020202055706772616465426561636f6e50726f78795631202020202020
VCoin
VCoin.sol
0x5ba0f310636c50a788bdd51a90f022cd15f9aad7
Solidity
pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(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 a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract ERC20 { uint256 public _totalSupply; string public name; string public symbol; uint8 public decimals; function totalSupply() public constant returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } //Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 contract ERC20Token is ERC20 { using SafeMath for uint256; function totalSupply() public constant returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { //require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } /** * @title ERC677 transferAndCall token interface * @dev See https://github.com/ethereum/EIPs/issues/677 for specification and * discussion. */ contract ERC677 { event Transfer(address indexed _from, address indexed _to, uint256 _amount, bytes _data); function transferAndCall(address _receiver, uint _amount, bytes _data) public; } /** * @title Receiver interface for ERC677 transferAndCall * @dev See https://github.com/ethereum/EIPs/issues/677 for specification and * discussion. */ contract ERC677Receiver { function tokenFallback(address _from, uint _amount, bytes _data) public; } contract ERC677Token is ERC677, ERC20Token { function transferAndCall(address _receiver, uint _amount, bytes _data) public { require(super.transfer(_receiver, _amount)); emit Transfer(msg.sender, _receiver, _amount, _data); // call receiver if (isContract(_receiver)) { ERC677Receiver to = ERC677Receiver(_receiver); to.tokenFallback(msg.sender, _amount, _data); } } function isContract(address _addr) internal view returns (bool) { uint len; assembly { len := extcodesize(_addr) } return len > 0; } } contract Splitable is ERC677Token, Ownable { uint32 public split; mapping (address => uint32) public splits; event Split(address indexed addr, uint32 multiplyer); constructor() public { split = 0; } function splitShare() onlyOwner public { require(split * 2 >= split); if (split == 0) split = 2; else split *= 2; claimShare(); } function isSplitable() public view returns (bool) { return splits[msg.sender] != split; } function claimShare() public { uint32 s = splits[msg.sender]; if (s == split) return; if (s == 0) s = 1; splits[msg.sender] = split; uint b = balances[msg.sender]; uint nb = b * split / s; balances[msg.sender] = nb; _totalSupply += nb - b; } function claimShare(address _u1, address _u2) public { uint32 s = splits[_u1]; if (s != split) { if (s == 0) s = 1; splits[_u1] = split; uint b = balances[_u1]; uint nb = b.mul(split / s); balances[_u1] = nb; _totalSupply += nb - b; } s = splits[_u2]; if (s != split) { if (s == 0) s = 1; splits[_u2] = split; b = balances[_u2]; nb = b.mul(split / s); balances[_u2] = nb; _totalSupply += nb - b; } } function transfer(address _to, uint256 _value) public returns (bool success) { if (splits[msg.sender] != splits[_to]) claimShare(msg.sender, _to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (splits[_from] != splits[_to]) claimShare(msg.sender, _to); return super.transferFrom(_from, _to, _value); } function transferAndCall(address _receiver, uint _amount, bytes _data) public { if (splits[_receiver] != splits[_receiver]) claimShare(msg.sender, _receiver); return super.transferAndCall(_receiver, _amount, _data); } } contract Lockable is ERC20Token, Ownable { using SafeMath for uint256; mapping (address => uint256) public lockAmounts; // function lock(address to, uint amount) public onlyOwner { // lockAmounts[to] = lockAmounts[to].add(amount); // } function unlock(address to, uint amount) public onlyOwner { lockAmounts[to] = lockAmounts[to].sub(amount); } function issueCoin(address to, uint amount) public onlyOwner { lockAmounts[to] = lockAmounts[to].add(amount); transfer(to, amount); // balances[to] = balances[to].add(amount); // balances[owner] = balances[owner].sub(amount); // emit Transfer(owner, to, amount); } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value + lockAmounts[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value + lockAmounts[_from]); return super.transferFrom(_from, _to, _value); } } contract VCoin is ERC677Token, Ownable, Splitable, Lockable { uint32 public purchaseNo; event Purchase(uint32 indexed purchaseNo, address from, uint value, bytes data); constructor() public { symbol = "VICT"; name = "Victory Token"; decimals = 18; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); purchaseNo = 1; } function () public payable { require(!isContract(msg.sender)); owner.transfer(msg.value); emit Purchase(purchaseNo++, msg.sender, msg.value, msg.data); //emit Transfer(owner, msg.sender, msg.value); } }
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"purchaseNo","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_amount","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"transferAndCall","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"splits","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"claimShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isSplitable","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"name":"unlock","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"splitShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"name":"issueCoin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_u1","type":"address"},{"name":"_u2","type":"address"}],"name":"claimShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"lockAmounts","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"split","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"purchaseNo","type":"uint32"},{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"Purchase","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"addr","type":"address"},{"indexed":false,"name":"multiplyer","type":"uint32"}],"name":"Split","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_amount","type":"uint256"},{"indexed":false,"name":"_data","type":"bytes"}],"name":"Transfer","type":"event"}]
v0.4.24+commit.e67f0147
false
200
Default
false
bzzr://199847e1b9feb8e0c5d2f570f030a32d5b4beb706f29af303a1bd28842c9b706
UserWallet
UserWallet.sol
0x51664e573049ab1ddbc2dc34f5b4fc290151cdb4
Solidity
pragma solidity ^0.4.24; contract AbstractSweeper { function sweepAll(address token) public returns (bool); function() public { revert(); } Controller controller; constructor(address _controller) public { controller = Controller(_controller); } modifier canSweep() { if(msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()){ revert(); } if(controller.halted()){ revert(); } _; } } contract Token { function balanceOf(address a) public pure returns (uint) { (a); return 0; } function transfer(address a, uint val) public pure returns (bool) { (a); (val); return false; } } contract DefaultSweeper is AbstractSweeper { constructor(address controller) AbstractSweeper(controller) public { } function sweepAll(address _token) public canSweep returns (bool) { bool success = false; address destination = controller.destination(); if(_token != address(0)){ Token token = Token(_token); success = token.transfer(destination, token.balanceOf(this)); }else{ success = destination.send(address(this).balance); } return success; } } contract UserWallet { AbstractSweeperList sweeperList; constructor(address _sweeperlist) public { sweeperList = AbstractSweeperList(_sweeperlist); } function() public payable { } function tokenFallback(address _from, uint _value, bytes _data) public pure { (_from); (_value); (_data); } function sweepAll(address _token) public returns (bool) { return sweeperList.sweeperOf(_token).delegatecall(msg.data); } } contract AbstractSweeperList { function sweeperOf(address _token) public returns (address); } contract Controller is AbstractSweeperList { address public owner; address public authorizedCaller; address public destination; bool public halted; event NewWalletCreated(address receiver); modifier onlyOwner() { if(msg.sender != owner){ revert(); } _; } modifier onlyAuthorizedCaller() { if(msg.sender != authorizedCaller){ revert(); } _; } modifier onlyAdmins() { if(msg.sender != authorizedCaller && msg.sender != owner){ revert(); } _; } constructor() public { owner = msg.sender; destination = msg.sender; authorizedCaller = msg.sender; } function setAuthorizedCaller(address _newCaller) public onlyOwner { authorizedCaller = _newCaller; } function setDestination(address _dest) public onlyOwner { destination = _dest; } function setOwner(address _owner) public onlyOwner { owner = _owner; } function newWallet() public onlyAdmins returns (address wallet) { wallet = address(new UserWallet(this)); emit NewWalletCreated(wallet); } function halt() public onlyAdmins { halted = true; } function start() public onlyOwner { halted = false; } address public defaultSweeper = address(new DefaultSweeper(this)); mapping (address => address) sweepers; function addSweeper(address _token, address _sweeper) public onlyOwner { sweepers[_token] = _sweeper; } function sweeperOf(address _token) public returns (address) { address sweeper = sweepers[_token]; if(sweeper == 0){ sweeper = defaultSweeper; } return sweeper; } }
[{"constant":true,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"sweepAll","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
200
0000000000000000000000007142eb34d2220152dedc5868745079bc6ffa0fdd
Default
None
false
bzzr://ec90d4e55fb69f839fa555767145d6ac7a8f1aa98ed098b09c220c4a34f02ba1
BYTC
BYTC.sol
0xc9a52fde36f4aeed087c2131d807ae5f8fd24df0
Solidity
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || 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) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } function destruct() public onlyOwner { selfdestruct(owner); } } contract ERC20Basic { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public; event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 public totalSupply; modifier onlyPayloadSize(uint256 size) { if(msg.data.length < size + 4) { revert(); } _; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) public { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract BYTC is StandardToken, Ownable { string public constant name = "佰优乐购"; string public constant symbol = "BYTC"; uint256 public constant decimals = 8; function BYTC() public { owner = msg.sender; totalSupply=100000000000000000; balances[owner]=totalSupply; } function () public { revert(); } }
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"destruct","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
v0.4.18+commit.9cf6e910
true
200
Default
false
bzzr://0118be04c0a1954dcea55e06fd6eef09b47e1df757ad407acd4c7cae021d8b0f
BucketLenderProxy
canonical-weth/contracts/WETH9.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
openzeppelin-solidity/contracts/math/Math.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
openzeppelin-solidity/contracts/math/SafeMath.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ 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 _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
openzeppelin-solidity/contracts/ownership/Ownable.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/AccessControlledBase.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/StaticAccessControlled.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/GeneralERC20.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/TokenProxy.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/Vault.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/ReentrancyGuard.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
openzeppelin-solidity/contracts/AddressUtils.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/Fraction.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/FractionMath.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/Exponent.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/MathHelpers.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/InterestImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/MarginState.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/LoanOwner.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/owner/PositionOwner.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/TransferInternal.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/TimestampHelper.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/MarginCommon.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/PayoutRecipient.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/CloseLoanDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/owner/ClosePositionDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/ClosePositionShared.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/ExchangeWrapper.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/ClosePositionImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/DepositCollateralImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/TypedSignature.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/LoanOfferingVerifier.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/BorrowShared.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/IncreasePositionImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/MarginStorage.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/LoanGetters.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/lender/MarginCallDelegator.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/LoanImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/MarginAdmin.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/MarginEvents.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/OpenPositionImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/PositionGetters.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/impl/TransferImpl.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/Margin.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/interfaces/OnlyMargin.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/external/lib/LoanOfferingParser.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/external/lib/MarginHelper.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/external/BucketLender/BucketLender.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/* solium-disable-next-line max-len*/ /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/lib/AdvancedTokenInteract.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title AdvancedTokenInteract * @author dYdX * * This library contains advanced functions for interacting with ERC20 tokens */ library AdvancedTokenInteract { using TokenInteract for address; /** * Checks if the spender has some amount of allowance. If it doesn't, then set allowance at * the maximum value. * * @param token Address of the ERC20 token * @param spender Argument of the allowance function * @param amount The minimum amount of allownce the the spender should be guaranteed */ function ensureAllowance( address token, address spender, uint256 amount ) internal { if (token.allowance(address(this), spender) < amount) { token.approve(spender, MathHelpers.maxUint256()); } } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
BucketLenderProxy
contracts/margin/external/BucketLender/BucketLenderProxy.sol
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
Solidity
/** * @title BucketLenderProxy * @author dYdX * * TokenProxy for BucketLender contracts */ contract BucketLenderProxy { using TokenInteract for address; using AdvancedTokenInteract for address; // ============ Constants ============ // Address of the WETH token address public WETH; // ============ Constructor ============ constructor( address weth ) public { WETH = weth; } // ============ Public Functions ============ /** * Fallback function. Disallows ETH to be sent to this contract without data except when * unwrapping WETH. */ function () external payable { require( // coverage-disable-line msg.sender == WETH, "BucketLenderProxy#fallback: Cannot recieve ETH directly unless unwrapping WETH" ); } /** * Send ETH directly to this contract, convert it to WETH, and sent it to a BucketLender * * @param bucketLender The address of the BucketLender contract to deposit into * @return The bucket number that was deposited into */ function depositEth( address bucketLender ) external payable returns (uint256) { address weth = WETH; require( weth == BucketLender(bucketLender).OWED_TOKEN(), "BucketLenderProxy#depositEth: BucketLender does not take WETH" ); WETH9(weth).deposit.value(msg.value)(); return depositInternal( bucketLender, weth, msg.value ); } /** * Deposits tokens from msg.sender into a BucketLender * * @param bucketLender The address of the BucketLender contract to deposit into * @param amount The amount of token to deposit * @return The bucket number that was deposited into */ function deposit( address bucketLender, uint256 amount ) external returns (uint256) { address token = BucketLender(bucketLender).OWED_TOKEN(); token.transferFrom(msg.sender, address(this), amount); return depositInternal( bucketLender, token, amount ); } /** * Withdraw tokens from a BucketLender * * @param bucketLender The address of the BucketLender contract to withdraw from * @param buckets The buckets to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket * @return Values corresponding to: * [0] = The number of owedTokens withdrawn * [1] = The number of heldTokens withdrawn */ function withdraw( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); transferInternal(owedToken, msg.sender, owedTokenAmount); transferInternal(heldToken, msg.sender, heldTokenAmount); return (owedTokenAmount, heldTokenAmount); } /** * Reinvest tokens by withdrawing them from one BucketLender and depositing them into another * * @param withdrawFrom The address of the BucketLender contract to withdraw from * @param depositInto The address of the BucketLender contract to deposit into * @param buckets The buckets to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket * @return Values corresponding to: * [0] = The bucket number that was deposited into * [1] = The number of owedTokens reinvested * [2] = The number of heldTokens withdrawn */ function rollover( address withdrawFrom, address depositInto, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256, uint256) { address owedToken = BucketLender(depositInto).OWED_TOKEN(); // the owedTokens of the two BucketLenders must be the same require ( owedToken == BucketLender(withdrawFrom).OWED_TOKEN(), "BucketLenderTokenProxy#rollover: Token mismatch" ); // withdraw from the first BucketLender ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(withdrawFrom).withdraw( buckets, maxWeights, msg.sender ); // reinvest any owedToken into the second BucketLender uint256 bucket = depositInternal( depositInto, owedToken, owedTokenAmount ); // return any heldToken to the msg.sender address heldToken = BucketLender(withdrawFrom).HELD_TOKEN(); transferInternal(heldToken, msg.sender, heldTokenAmount); return (bucket, owedTokenAmount, heldTokenAmount); } // ============ Private Functions ============ function depositInternal( address bucketLender, address token, uint256 amount ) private returns (uint256) { token.ensureAllowance(bucketLender, amount); return BucketLender(bucketLender).deposit(msg.sender, amount); } function transferInternal( address token, address recipient, uint256 amount ) private { address weth = WETH; if (token == weth) { if (amount != 0) { WETH9(weth).withdraw(amount); msg.sender.transfer(amount); } } else { token.transfer(recipient, amount); } } }
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
v0.4.24+commit.e67f0147
true
10,000
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Default
false
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
ERC1967Proxy
ERC1967Proxy.sol
0xa9fd280e65f3519da4aa0ace95ad0d6f867f9533
Solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } } /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; } abstract contract Proxiable is UUPSUpgradeable { function _authorizeUpgrade(address newImplementation) internal override { _beforeUpgrade(newImplementation); } function _beforeUpgrade(address newImplementation) internal virtual; } contract ChildOfProxiable is Proxiable { function _beforeUpgrade(address newImplementation) internal virtual override {} } /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins. contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {} }
[{"inputs":[{"internalType":"address","name":"_logic","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"stateMutability":"payable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"stateMutability":"payable","type":"fallback"},{"stateMutability":"payable","type":"receive"}]
v0.8.2+commit.661d1103
true
200
0000000000000000000000008fd46e7f74e5976837135a42c4bfc946fe5a229f00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000044485cc9550000000000000000000000001111111111accdf36dbee012fc26bb9fcc1d140d0000000000000000000000009978be4de5beb786da4727a545b14fec2266511700000000000000000000000000000000000000000000000000000000
Default
MIT
false
ipfs://9b8470f06e8a3960c912103fc2be177edaad69584ee3c7d2809ee737e79408e7
SaffronLPBalanceToken
contracts/lib/Address.sol
0x96853eadcf9da67d6f7a4b6ad28bdc81a96c2188
Solidity
pragma solidity ^0.7.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
[{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool_address","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"set_governance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]
v0.7.4+commit.3f05b770
true
99,999
000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002353616666726f6e204c502065706f6368203133205320444149207072696e636970616c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007534146462d4c5000000000000000000000000000000000000000000000000000
Default
MIT
false
ipfs://987173ae06a00aaf418e92fd1f57b81c2c1341970dc2d243d753c1adfa0346ca