Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
54 | // emitted when admin withdraws equityNote that `equityAvailableBefore` indicates equity before `amount` was removed. / | event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner);
| event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner);
| 19,267 |
7 | // MarriageCertificateIssuer Issue marriage certificate.Don't issue as ERC720 for saving gas cost purpose. We don't assume to trasfer token / | contract MarriageCertificateIssuer is Ownable {
using SafeMath for uint256;
uint256 public FEE = 20000000000000000;
uint256 private deposits;
uint256 private prefix = 20000000;
struct Certificate {
bytes32 bride;
bytes32 groom;
}
// Certificate ID range is 20000001 to 4294967295
Certificate[] public certificates;
/**
* @dev Emitted when certificate issued
*/
event Issued (uint256 indexed certificateID, bytes32 bride, bytes32 groom);
/**
* @dev Reverts if fee is not same as FEE
*/
modifier confirmFee() {
require(msg.value == FEE, "Should pay exact 0.02 ETH");
_;
}
/**
* @dev Issue marriage certificate
* @param _bride One persono name got married
* @param _groom The other persono name got married
*/
function issueCertificate(bytes32 _bride, bytes32 _groom) public confirmFee payable returns (uint256) {
uint256 certificateID = certificates.push(Certificate({
bride: _bride,
groom: _groom
})).add(prefix);
uint256 amount = msg.value;
deposits = deposits.add(amount);
emit Issued(certificateID, _bride, _groom);
return certificateID;
}
/**
* @dev Withdraw accumulated fee by owner
*/
function withdrawFee(address payable payee) public onlyOwner {
uint256 payment = deposits;
deposits = 0;
payee.transfer(payment);
}
/**
* @dev See accumulated fee by owner
*/
function depositedFee() public view onlyOwner returns (uint256) {
return deposits;
}
}
| contract MarriageCertificateIssuer is Ownable {
using SafeMath for uint256;
uint256 public FEE = 20000000000000000;
uint256 private deposits;
uint256 private prefix = 20000000;
struct Certificate {
bytes32 bride;
bytes32 groom;
}
// Certificate ID range is 20000001 to 4294967295
Certificate[] public certificates;
/**
* @dev Emitted when certificate issued
*/
event Issued (uint256 indexed certificateID, bytes32 bride, bytes32 groom);
/**
* @dev Reverts if fee is not same as FEE
*/
modifier confirmFee() {
require(msg.value == FEE, "Should pay exact 0.02 ETH");
_;
}
/**
* @dev Issue marriage certificate
* @param _bride One persono name got married
* @param _groom The other persono name got married
*/
function issueCertificate(bytes32 _bride, bytes32 _groom) public confirmFee payable returns (uint256) {
uint256 certificateID = certificates.push(Certificate({
bride: _bride,
groom: _groom
})).add(prefix);
uint256 amount = msg.value;
deposits = deposits.add(amount);
emit Issued(certificateID, _bride, _groom);
return certificateID;
}
/**
* @dev Withdraw accumulated fee by owner
*/
function withdrawFee(address payable payee) public onlyOwner {
uint256 payment = deposits;
deposits = 0;
payee.transfer(payment);
}
/**
* @dev See accumulated fee by owner
*/
function depositedFee() public view onlyOwner returns (uint256) {
return deposits;
}
}
| 8,499 |
35 | // Basis Cash Treasury contract Monetary policy logic to adjust supplies of basis cash assets Summer Smith & Rick Sanchez / | contract Treasury is ContractGuard, Epoch {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
/* ========== STATE VARIABLES ========== */
// ========== FLAGS
bool public migrated = false;
bool public initialized = false;
// ========== CORE
address public fund;
address public cash;
address public bond;
address public share;
address public shareBoardroom;
address public lpBoardroom;
address public bondRewardPool;
//address public bondOracle;
//address public seigniorageOracle;
address public oracle;
// ========== PARAMS
uint256 public cashPriceOne;
uint256 public cashPriceCeiling;
uint256 public cashPriceFloor;
uint256 public cashPriceBondReward;
uint256 private accumulatedSeigniorage = 0;
uint256 private accumulatedDebt = 0;
uint256 public bondPriceOnGAC;
uint256 public minBondPriceOnGAC;
uint256 public bondPriceOnGACDelta;
uint256 public fundAllocationRate = 3; // %
uint256 public maxInflationRate = 10;
uint256 public debtAddRate = 2;
uint256 public maxDebtRate = 20;
// ========== MIGRATE
address public legacyTreasury;
/* ========== CONSTRUCTOR ========== */
constructor(
address _cash,
address _bond,
address _share,
address _oracle,
address _shareBoardroom,
address _lpBoardroom,
address _bondRewardPool,
address _fund,
uint256 _startTime
) public Epoch(6 hours, _startTime, 0) {
cash = _cash;
bond = _bond;
share = _share;
oracle = _oracle;
shareBoardroom = _shareBoardroom;
lpBoardroom = _lpBoardroom;
bondRewardPool = _bondRewardPool;
fund = _fund;
cashPriceOne = 10**18;
cashPriceCeiling = uint256(101).mul(cashPriceOne).div(10**2);
cashPriceFloor = uint256(99).mul(cashPriceOne).div(10**2);
cashPriceBondReward = uint256(95).mul(cashPriceOne).div(10**2);
bondPriceOnGAC = 10**18;
minBondPriceOnGAC = 5 * 10**17;
bondPriceOnGACDelta = 2 * 10 ** 16;
}
/* =================== Modifier =================== */
modifier checkMigration {
require(!migrated, 'Treasury: migrated');
_;
}
modifier checkOperator {
require(
IBasisAsset(cash).operator() == address(this) &&
IBasisAsset(bond).operator() == address(this) &&
IBasisAsset(share).operator() == address(this) &&
Operator(shareBoardroom).operator() == address(this) &&
Operator(lpBoardroom).operator() == address(this) &&
Operator(bondRewardPool).operator() == address(this),
'Treasury: need more permission'
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
// budget
function getReserve() public view returns (uint256) {
return accumulatedSeigniorage;
}
// debt
function getDebt() public view returns (uint256) {
return accumulatedDebt;
}
// oracle
function getOraclePrice() public view returns (uint256) {
return _getCashPrice(oracle);
}
function _getCashPrice(address _oracle) internal view returns (uint256) {
try IOracle(_oracle).consult(cash, 1e18) returns (uint256 price) {
return price;
} catch {
revert('Treasury: failed to consult cash price from the oracle');
}
}
/* ========== GOVERNANCE ========== */
function setLegacyTreasury(address _legacyTreasury) public onlyOperator {
legacyTreasury = _legacyTreasury;
}
function initialize(
uint256 _accumulatedSeigniorage,
uint256 _accumulatedDebt,
uint256 _bondPriceOnGAC
) public {
require(!initialized, 'Treasury: initialized');
require(msg.sender == legacyTreasury, 'Treasury: on legacy treasury');
accumulatedSeigniorage = _accumulatedSeigniorage;
accumulatedDebt = _accumulatedDebt;
bondPriceOnGAC = _bondPriceOnGAC;
initialized = true;
emit Initialized(msg.sender, block.number);
}
function migrate(address target) public onlyOperator checkOperator {
require(!migrated, 'Treasury: migrated');
// cash
Operator(cash).transferOperator(target);
Operator(cash).transferOwnership(target);
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
// bond
Operator(bond).transferOperator(target);
Operator(bond).transferOwnership(target);
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
// share
Operator(share).transferOperator(target);
Operator(share).transferOwnership(target);
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
// params
ITreasury(target).initialize(
accumulatedSeigniorage,
accumulatedDebt,
bondPriceOnGAC
);
migrated = true;
emit Migration(target);
}
function setFund(address newFund) public onlyOperator {
fund = newFund;
emit ContributionPoolChanged(msg.sender, newFund);
}
function setFundAllocationRate(uint256 rate) public onlyOperator {
fundAllocationRate = rate;
emit ContributionPoolRateChanged(msg.sender, rate);
}
function setMaxInflationRate(uint256 rate) public onlyOperator {
maxInflationRate = rate;
emit MaxInflationRateChanged(msg.sender, rate);
}
function setDebtAddRate(uint256 rate) public onlyOperator {
debtAddRate = rate;
emit DebtAddRateChanged(msg.sender, rate);
}
function setMaxDebtRate(uint256 rate) public onlyOperator {
maxDebtRate = rate;
emit MaxDebtRateChanged(msg.sender, rate);
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateCashPrice() internal {
try IOracle(oracle).update() {} catch {}
}
function buyBonds(uint256 amount)
external
onlyGaeaBlock
checkMigration
checkStartTime
checkOperator
{
uint256 cashPrice = _getCashPrice(oracle);
require(
cashPrice < cashPriceOne, // price < $1
'Treasury: cashPrice not eligible for bond purchase'
);
uint256 burnAmount = Math.min(
amount,
accumulatedDebt.mul(bondPriceOnGAC).div(1e18)
);
require(burnAmount > 0, 'Treasury: cannot purchase bonds with zero amount');
uint256 mintBondAmount = burnAmount.mul(1e18).div(bondPriceOnGAC);
IBasisAsset(cash).burnFrom(msg.sender, burnAmount);
IBasisAsset(bond).mint(msg.sender, mintBondAmount);
accumulatedDebt = accumulatedDebt.sub(mintBondAmount);
_updateCashPrice();
emit BoughtBonds(msg.sender, burnAmount);
}
function redeemBonds(uint256 amount)
external
onlyGaeaBlock
checkMigration
checkStartTime
checkOperator
{
uint256 cashPrice = _getCashPrice(oracle);
require(
cashPrice > cashPriceOne, // price > $1
'Treasury: cashPrice not eligible for bond redeem'
);
uint256 redeemAmount = Math.min(accumulatedSeigniorage, amount);
require(redeemAmount > 0, 'Treasury: cannot redeem bonds with zero amount');
accumulatedSeigniorage = accumulatedSeigniorage.sub(redeemAmount);
IBasisAsset(bond).burnFrom(msg.sender, redeemAmount);
IERC20(cash).safeTransfer(msg.sender, redeemAmount);
_updateCashPrice();
emit RedeemedBonds(msg.sender, redeemAmount);
}
function allocateSeigniorage()
external
onlyGaeaBlock
checkMigration
checkStartTime
checkEpoch
checkOperator
{
_updateCashPrice();
uint256 cashPrice = _getCashPrice(oracle);
// circulating supply
uint256 cashSupply = IERC20(cash).totalSupply().sub(
accumulatedSeigniorage
);
// bond reward
if (cashPrice <= cashPriceBondReward) {
uint256 rewardAmount = IERC20(bond).totalSupply().div(100);
IBasisAsset(bond).mint(bondRewardPool, rewardAmount);
IONBRewardPool(bondRewardPool).notifyRewardAmount(rewardAmount);
emit BondReward(block.timestamp, rewardAmount);
}
// add debt
if (cashPrice <= cashPriceFloor) {
uint256 addDebt = cashSupply.mul(debtAddRate).div(100);
uint256 maxDebt = cashSupply.mul(maxDebtRate).div(100);
accumulatedDebt = accumulatedDebt.add(addDebt);
if (accumulatedDebt > maxDebt) {
accumulatedDebt = maxDebt;
}
bondPriceOnGAC = bondPriceOnGAC.sub(bondPriceOnGACDelta);
if (bondPriceOnGAC <= minBondPriceOnGAC) {
bondPriceOnGAC = minBondPriceOnGAC;
}
}
// clear the debt
if (cashPrice > cashPriceFloor) {
accumulatedDebt = 0;
bondPriceOnGAC = 10**18;
}
if (cashPrice <= cashPriceCeiling) {
return; // just advance epoch instead revert
}
uint256 percentage = cashPrice.sub(cashPriceOne);
uint256 seigniorage = cashSupply.mul(percentage).div(1e18);
uint256 maxSeigniorage = cashSupply.mul(maxInflationRate).div(100);
if (seigniorage > maxSeigniorage) {
seigniorage = maxSeigniorage;
}
IBasisAsset(cash).mint(address(this), seigniorage);
// ======================== BIP-3
uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100);
if (fundReserve > 0) {
IERC20(cash).safeApprove(fund, fundReserve);
ISimpleERCFund(fund).deposit(
cash,
fundReserve,
'Treasury: Seigniorage Allocation'
);
emit ContributionPoolFunded(now, fundReserve);
}
seigniorage = seigniorage.sub(fundReserve);
// ======================== BIP-4
uint256 treasuryReserve = Math.min(
seigniorage.div(2), // only 50% inflation to treasury
IERC20(bond).totalSupply().sub(accumulatedSeigniorage)
);
if (treasuryReserve > 0) {
accumulatedSeigniorage = accumulatedSeigniorage.add(
treasuryReserve
);
emit TreasuryFunded(now, treasuryReserve);
}
// boardroom
uint256 boardroomReserve = seigniorage.sub(treasuryReserve);
if (boardroomReserve > 0) {
uint256 shareBoardroomReserve = boardroomReserve.mul(6).div(10);
uint256 lpBoardroomReserve = boardroomReserve.sub(shareBoardroomReserve);
IERC20(cash).safeApprove(shareBoardroom, shareBoardroomReserve);
IBoardroom(shareBoardroom).allocateSeigniorage(shareBoardroomReserve);
IERC20(cash).safeApprove(lpBoardroom, lpBoardroomReserve);
IBoardroom(lpBoardroom).allocateSeigniorage(lpBoardroomReserve);
emit BoardroomFunded(now, boardroomReserve);
}
}
// GOV
event Initialized(address indexed executor, uint256 at);
event Migration(address indexed target);
event ContributionPoolChanged(address indexed operator, address newFund);
event ContributionPoolRateChanged(
address indexed operator,
uint256 newRate
);
event MaxInflationRateChanged(
address indexed operator,
uint256 newRate
);
event DebtAddRateChanged(
address indexed operator,
uint256 newRate
);
event MaxDebtRateChanged(
address indexed operator,
uint256 newRate
);
// CORE
event RedeemedBonds(address indexed from, uint256 amount);
event BoughtBonds(address indexed from, uint256 amount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event BondReward(uint256 timestamp, uint256 seigniorage);
event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage);
}
| contract Treasury is ContractGuard, Epoch {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
/* ========== STATE VARIABLES ========== */
// ========== FLAGS
bool public migrated = false;
bool public initialized = false;
// ========== CORE
address public fund;
address public cash;
address public bond;
address public share;
address public shareBoardroom;
address public lpBoardroom;
address public bondRewardPool;
//address public bondOracle;
//address public seigniorageOracle;
address public oracle;
// ========== PARAMS
uint256 public cashPriceOne;
uint256 public cashPriceCeiling;
uint256 public cashPriceFloor;
uint256 public cashPriceBondReward;
uint256 private accumulatedSeigniorage = 0;
uint256 private accumulatedDebt = 0;
uint256 public bondPriceOnGAC;
uint256 public minBondPriceOnGAC;
uint256 public bondPriceOnGACDelta;
uint256 public fundAllocationRate = 3; // %
uint256 public maxInflationRate = 10;
uint256 public debtAddRate = 2;
uint256 public maxDebtRate = 20;
// ========== MIGRATE
address public legacyTreasury;
/* ========== CONSTRUCTOR ========== */
constructor(
address _cash,
address _bond,
address _share,
address _oracle,
address _shareBoardroom,
address _lpBoardroom,
address _bondRewardPool,
address _fund,
uint256 _startTime
) public Epoch(6 hours, _startTime, 0) {
cash = _cash;
bond = _bond;
share = _share;
oracle = _oracle;
shareBoardroom = _shareBoardroom;
lpBoardroom = _lpBoardroom;
bondRewardPool = _bondRewardPool;
fund = _fund;
cashPriceOne = 10**18;
cashPriceCeiling = uint256(101).mul(cashPriceOne).div(10**2);
cashPriceFloor = uint256(99).mul(cashPriceOne).div(10**2);
cashPriceBondReward = uint256(95).mul(cashPriceOne).div(10**2);
bondPriceOnGAC = 10**18;
minBondPriceOnGAC = 5 * 10**17;
bondPriceOnGACDelta = 2 * 10 ** 16;
}
/* =================== Modifier =================== */
modifier checkMigration {
require(!migrated, 'Treasury: migrated');
_;
}
modifier checkOperator {
require(
IBasisAsset(cash).operator() == address(this) &&
IBasisAsset(bond).operator() == address(this) &&
IBasisAsset(share).operator() == address(this) &&
Operator(shareBoardroom).operator() == address(this) &&
Operator(lpBoardroom).operator() == address(this) &&
Operator(bondRewardPool).operator() == address(this),
'Treasury: need more permission'
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
// budget
function getReserve() public view returns (uint256) {
return accumulatedSeigniorage;
}
// debt
function getDebt() public view returns (uint256) {
return accumulatedDebt;
}
// oracle
function getOraclePrice() public view returns (uint256) {
return _getCashPrice(oracle);
}
function _getCashPrice(address _oracle) internal view returns (uint256) {
try IOracle(_oracle).consult(cash, 1e18) returns (uint256 price) {
return price;
} catch {
revert('Treasury: failed to consult cash price from the oracle');
}
}
/* ========== GOVERNANCE ========== */
function setLegacyTreasury(address _legacyTreasury) public onlyOperator {
legacyTreasury = _legacyTreasury;
}
function initialize(
uint256 _accumulatedSeigniorage,
uint256 _accumulatedDebt,
uint256 _bondPriceOnGAC
) public {
require(!initialized, 'Treasury: initialized');
require(msg.sender == legacyTreasury, 'Treasury: on legacy treasury');
accumulatedSeigniorage = _accumulatedSeigniorage;
accumulatedDebt = _accumulatedDebt;
bondPriceOnGAC = _bondPriceOnGAC;
initialized = true;
emit Initialized(msg.sender, block.number);
}
function migrate(address target) public onlyOperator checkOperator {
require(!migrated, 'Treasury: migrated');
// cash
Operator(cash).transferOperator(target);
Operator(cash).transferOwnership(target);
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
// bond
Operator(bond).transferOperator(target);
Operator(bond).transferOwnership(target);
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
// share
Operator(share).transferOperator(target);
Operator(share).transferOwnership(target);
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
// params
ITreasury(target).initialize(
accumulatedSeigniorage,
accumulatedDebt,
bondPriceOnGAC
);
migrated = true;
emit Migration(target);
}
function setFund(address newFund) public onlyOperator {
fund = newFund;
emit ContributionPoolChanged(msg.sender, newFund);
}
function setFundAllocationRate(uint256 rate) public onlyOperator {
fundAllocationRate = rate;
emit ContributionPoolRateChanged(msg.sender, rate);
}
function setMaxInflationRate(uint256 rate) public onlyOperator {
maxInflationRate = rate;
emit MaxInflationRateChanged(msg.sender, rate);
}
function setDebtAddRate(uint256 rate) public onlyOperator {
debtAddRate = rate;
emit DebtAddRateChanged(msg.sender, rate);
}
function setMaxDebtRate(uint256 rate) public onlyOperator {
maxDebtRate = rate;
emit MaxDebtRateChanged(msg.sender, rate);
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateCashPrice() internal {
try IOracle(oracle).update() {} catch {}
}
function buyBonds(uint256 amount)
external
onlyGaeaBlock
checkMigration
checkStartTime
checkOperator
{
uint256 cashPrice = _getCashPrice(oracle);
require(
cashPrice < cashPriceOne, // price < $1
'Treasury: cashPrice not eligible for bond purchase'
);
uint256 burnAmount = Math.min(
amount,
accumulatedDebt.mul(bondPriceOnGAC).div(1e18)
);
require(burnAmount > 0, 'Treasury: cannot purchase bonds with zero amount');
uint256 mintBondAmount = burnAmount.mul(1e18).div(bondPriceOnGAC);
IBasisAsset(cash).burnFrom(msg.sender, burnAmount);
IBasisAsset(bond).mint(msg.sender, mintBondAmount);
accumulatedDebt = accumulatedDebt.sub(mintBondAmount);
_updateCashPrice();
emit BoughtBonds(msg.sender, burnAmount);
}
function redeemBonds(uint256 amount)
external
onlyGaeaBlock
checkMigration
checkStartTime
checkOperator
{
uint256 cashPrice = _getCashPrice(oracle);
require(
cashPrice > cashPriceOne, // price > $1
'Treasury: cashPrice not eligible for bond redeem'
);
uint256 redeemAmount = Math.min(accumulatedSeigniorage, amount);
require(redeemAmount > 0, 'Treasury: cannot redeem bonds with zero amount');
accumulatedSeigniorage = accumulatedSeigniorage.sub(redeemAmount);
IBasisAsset(bond).burnFrom(msg.sender, redeemAmount);
IERC20(cash).safeTransfer(msg.sender, redeemAmount);
_updateCashPrice();
emit RedeemedBonds(msg.sender, redeemAmount);
}
function allocateSeigniorage()
external
onlyGaeaBlock
checkMigration
checkStartTime
checkEpoch
checkOperator
{
_updateCashPrice();
uint256 cashPrice = _getCashPrice(oracle);
// circulating supply
uint256 cashSupply = IERC20(cash).totalSupply().sub(
accumulatedSeigniorage
);
// bond reward
if (cashPrice <= cashPriceBondReward) {
uint256 rewardAmount = IERC20(bond).totalSupply().div(100);
IBasisAsset(bond).mint(bondRewardPool, rewardAmount);
IONBRewardPool(bondRewardPool).notifyRewardAmount(rewardAmount);
emit BondReward(block.timestamp, rewardAmount);
}
// add debt
if (cashPrice <= cashPriceFloor) {
uint256 addDebt = cashSupply.mul(debtAddRate).div(100);
uint256 maxDebt = cashSupply.mul(maxDebtRate).div(100);
accumulatedDebt = accumulatedDebt.add(addDebt);
if (accumulatedDebt > maxDebt) {
accumulatedDebt = maxDebt;
}
bondPriceOnGAC = bondPriceOnGAC.sub(bondPriceOnGACDelta);
if (bondPriceOnGAC <= minBondPriceOnGAC) {
bondPriceOnGAC = minBondPriceOnGAC;
}
}
// clear the debt
if (cashPrice > cashPriceFloor) {
accumulatedDebt = 0;
bondPriceOnGAC = 10**18;
}
if (cashPrice <= cashPriceCeiling) {
return; // just advance epoch instead revert
}
uint256 percentage = cashPrice.sub(cashPriceOne);
uint256 seigniorage = cashSupply.mul(percentage).div(1e18);
uint256 maxSeigniorage = cashSupply.mul(maxInflationRate).div(100);
if (seigniorage > maxSeigniorage) {
seigniorage = maxSeigniorage;
}
IBasisAsset(cash).mint(address(this), seigniorage);
// ======================== BIP-3
uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100);
if (fundReserve > 0) {
IERC20(cash).safeApprove(fund, fundReserve);
ISimpleERCFund(fund).deposit(
cash,
fundReserve,
'Treasury: Seigniorage Allocation'
);
emit ContributionPoolFunded(now, fundReserve);
}
seigniorage = seigniorage.sub(fundReserve);
// ======================== BIP-4
uint256 treasuryReserve = Math.min(
seigniorage.div(2), // only 50% inflation to treasury
IERC20(bond).totalSupply().sub(accumulatedSeigniorage)
);
if (treasuryReserve > 0) {
accumulatedSeigniorage = accumulatedSeigniorage.add(
treasuryReserve
);
emit TreasuryFunded(now, treasuryReserve);
}
// boardroom
uint256 boardroomReserve = seigniorage.sub(treasuryReserve);
if (boardroomReserve > 0) {
uint256 shareBoardroomReserve = boardroomReserve.mul(6).div(10);
uint256 lpBoardroomReserve = boardroomReserve.sub(shareBoardroomReserve);
IERC20(cash).safeApprove(shareBoardroom, shareBoardroomReserve);
IBoardroom(shareBoardroom).allocateSeigniorage(shareBoardroomReserve);
IERC20(cash).safeApprove(lpBoardroom, lpBoardroomReserve);
IBoardroom(lpBoardroom).allocateSeigniorage(lpBoardroomReserve);
emit BoardroomFunded(now, boardroomReserve);
}
}
// GOV
event Initialized(address indexed executor, uint256 at);
event Migration(address indexed target);
event ContributionPoolChanged(address indexed operator, address newFund);
event ContributionPoolRateChanged(
address indexed operator,
uint256 newRate
);
event MaxInflationRateChanged(
address indexed operator,
uint256 newRate
);
event DebtAddRateChanged(
address indexed operator,
uint256 newRate
);
event MaxDebtRateChanged(
address indexed operator,
uint256 newRate
);
// CORE
event RedeemedBonds(address indexed from, uint256 amount);
event BoughtBonds(address indexed from, uint256 amount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event BondReward(uint256 timestamp, uint256 seigniorage);
event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage);
}
| 33,014 |
10 | // TODO: Update to burnFrom once https:github.com/OpenZeppelin/zeppelin-solidity/pull/870 is merged | require(token.transferFrom(msg.sender, this, newVersionCost));
token.burn(newVersionCost);
| require(token.transferFrom(msg.sender, this, newVersionCost));
token.burn(newVersionCost);
| 7,070 |
231 | // Check if a specific currency's rate hasn't been updated for longer than the stale period. / | function rateIsStale(bytes32 currencyKey)
public
view
returns (bool)
| function rateIsStale(bytes32 currencyKey)
public
view
returns (bool)
| 22,739 |
117 | // Underlying token | IERC20 token;
| IERC20 token;
| 51,397 |
59 | // Called when new token are issued | event Issue(uint amount);
| event Issue(uint amount);
| 5,012 |
69 | // buyer limits check | bool successByrlAFinl;
(successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr);
require( successSlrl == true && successByrlAFinl == true);
return true;
| bool successByrlAFinl;
(successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr);
require( successSlrl == true && successByrlAFinl == true);
return true;
| 46,164 |
32 | // Constructor that gives msg.sender all of existing tokens./ | constructor() UE() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| constructor() UE() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| 9,495 |
64 | // Returns whether `_addressToCheck` is the owner of `quantity` tokens sequentially starting from `startID`. Requirements: - `startID` token and all sequential tokens must exist. / | function multiOwnerCheck(address _addressToCheck, uint256 startID, uint256 quantity) internal view returns (bool) {
require(quantity > 1, "Low Quantity");
unchecked {
for (uint256 i; i < quantity; i++) {
if (ownerOf(startID + i) != _addressToCheck){
return false;
}
}
}
return true;
}
| function multiOwnerCheck(address _addressToCheck, uint256 startID, uint256 quantity) internal view returns (bool) {
require(quantity > 1, "Low Quantity");
unchecked {
for (uint256 i; i < quantity; i++) {
if (ownerOf(startID + i) != _addressToCheck){
return false;
}
}
}
return true;
}
| 48,139 |
65 | // Selling fees | if (automatedMarketMakerPairs[to] && to != address(_router) ){
totalFeeFortx = 0;
mktAmount = amount * sellmktFee/100;
liqAmount = amount * sellliqFee/100;
prizePoolAmount = amount * sellprizePool/100;
gameAmount = amount *sellP2EPool/100;
charityAmount = amount *sellCharity/100;
totalFeeFortx = mktAmount + liqAmount + prizePoolAmount + gameAmount + charityAmount;
}
| if (automatedMarketMakerPairs[to] && to != address(_router) ){
totalFeeFortx = 0;
mktAmount = amount * sellmktFee/100;
liqAmount = amount * sellliqFee/100;
prizePoolAmount = amount * sellprizePool/100;
gameAmount = amount *sellP2EPool/100;
charityAmount = amount *sellCharity/100;
totalFeeFortx = mktAmount + liqAmount + prizePoolAmount + gameAmount + charityAmount;
}
| 32,075 |
6 | // Must return the account's _current_ UNT earnings (as of current blockchain state). Used in the frontend. / | function earned(address _account) override external view returns(uint256){
if(_account == IExhibition(exhibition).controller()){
uint256 endTime = block.timestamp;
if (endTime < allocationEnd ) {
return 0;
}
if(endTime > exhibitionEnd){
endTime = exhibitionEnd;
}
return ( ( endTime - allocationEnd ) * untRateExhibitionController ) - paidToController;
}
(IUniftyGovernanceConsumer con,address peer,,,) = gov.accountInfo(_account);
if(con != this || peer != exhibition || exhibition == address(0)){
return 0;
}
return ( accountReserved[_account] + ( ( collectedUnt * accountPrevAmount[_account] ) / 10**18 ) ) - accountDebt[_account];
}
| function earned(address _account) override external view returns(uint256){
if(_account == IExhibition(exhibition).controller()){
uint256 endTime = block.timestamp;
if (endTime < allocationEnd ) {
return 0;
}
if(endTime > exhibitionEnd){
endTime = exhibitionEnd;
}
return ( ( endTime - allocationEnd ) * untRateExhibitionController ) - paidToController;
}
(IUniftyGovernanceConsumer con,address peer,,,) = gov.accountInfo(_account);
if(con != this || peer != exhibition || exhibition == address(0)){
return 0;
}
return ( accountReserved[_account] + ( ( collectedUnt * accountPrevAmount[_account] ) / 10**18 ) ) - accountDebt[_account];
}
| 18,580 |
11 | // Origin chain id. | uint256 originChainId;
| uint256 originChainId;
| 29,415 |
114 | // .01 ETH | uint256 public MINIMUM = 1000000000000000;
| uint256 public MINIMUM = 1000000000000000;
| 10,746 |
12 | // known problem: settle reductions/growths need to be tied to the transaction that incurred it and adjust ownership respectively solution: if a synth is exchanged, record which address called the function, then later if a settle is needed adjustments can be issued to said holder | /* function clear(string memory synthname) public {
bytes32 synthcode = stringToBytes32(synthname);
(bool outcome1, bool outcome2) = clearPendingSwaps(synthcode);
emit ResultBools(outcome1, outcome2);
}
| /* function clear(string memory synthname) public {
bytes32 synthcode = stringToBytes32(synthname);
(bool outcome1, bool outcome2) = clearPendingSwaps(synthcode);
emit ResultBools(outcome1, outcome2);
}
| 29,717 |
87 | // Gets all the bid data related to a token/tokenId The id of the token/ return bid information | function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
| function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
| 20,899 |
32 | // Partnerships and Advisory vested amount 7.2% | uint256 partnershipsAdvisoryVested = totalAmount * 72 / 1000;
uint256 privateSales = 2970000000000000000000000;
uint256 preSale = 2397307557007329968290000;
transferTokens(auctusCoreTeam, bounty, reserveForFuture, preSale, partnershipsAdvisoryVested, partnershipsAdvisoryFree, privateSales);
remainingTokens = totalAmount - auctusCoreTeam - bounty - reserveForFuture - preSale - partnershipsAdvisoryVested - partnershipsAdvisoryFree - privateSales;
saleWasSet = true;
| uint256 partnershipsAdvisoryVested = totalAmount * 72 / 1000;
uint256 privateSales = 2970000000000000000000000;
uint256 preSale = 2397307557007329968290000;
transferTokens(auctusCoreTeam, bounty, reserveForFuture, preSale, partnershipsAdvisoryVested, partnershipsAdvisoryFree, privateSales);
remainingTokens = totalAmount - auctusCoreTeam - bounty - reserveForFuture - preSale - partnershipsAdvisoryVested - partnershipsAdvisoryFree - privateSales;
saleWasSet = true;
| 37,605 |
16 | // similar to take(), but with the block height joined to calculate return./for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests./ return amount of interests and the block height. | function takeWithBlock() external view returns (uint256, uint256);
| function takeWithBlock() external view returns (uint256, uint256);
| 22,926 |
468 | // Gets USB balance of the urn in the vat | uint USB = VatLike(vat).USB(urn);
| uint USB = VatLike(vat).USB(urn);
| 78,431 |
210 | // - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.- If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. / | function safeTransferFrom(
| function safeTransferFrom(
| 3,177 |
10 | // Update the playerHatchet mapping. | playerHatchet[msg.sender].value = _tokenId;
playerHatchet[msg.sender].isData = true;
| playerHatchet[msg.sender].value = _tokenId;
playerHatchet[msg.sender].isData = true;
| 19,607 |
182 | // term(k) = numer / denom = (product(a - i - 1, i=1-->k)x^k) / (k!) each iteration, multiply previous term by (a-(k-1))x / k continue until term is less than precision | for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
| for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
| 13,141 |
124 | // Tax on the total bonding curve funds | uint256 taxOnOriginal = _tokens.mul(_curationTaxPercentage).div(MAX_PPM);
| uint256 taxOnOriginal = _tokens.mul(_curationTaxPercentage).div(MAX_PPM);
| 84,263 |
140 | // Function to check the _amount of tokens that an owner has allowed to a _spender. _owner The address which owns the funds. _spender The address which will spend the funds.return The number of tokens still available for the _spender. / | function allowance(address _owner, address _spender)
public
view
returns (uint256)
| function allowance(address _owner, address _spender)
public
view
returns (uint256)
| 4,348 |
105 | // the owner role is used to add values to the store, but it can't update them | bytes32 public constant ROLE_OWNER = keccak256("ROLE_OWNER");
| bytes32 public constant ROLE_OWNER = keccak256("ROLE_OWNER");
| 14,508 |
8 | // Returns current color in the box./Returns only a string./ return The current color of in the box state | function getColor() public view returns (string memory) {
require(!shouldRevert, "Set to revert");
return color;
}
| function getColor() public view returns (string memory) {
require(!shouldRevert, "Set to revert");
return color;
}
| 38,272 |
15 | // start rewriting addresses in eth deposits | function startRewriteAddress() external override onlyOwner {
require(!shouldRewriteSender, "ALREADY_REWRITING");
shouldRewriteSender = true;
emit RewriteToggled(true);
}
| function startRewriteAddress() external override onlyOwner {
require(!shouldRewriteSender, "ALREADY_REWRITING");
shouldRewriteSender = true;
emit RewriteToggled(true);
}
| 48,464 |
78 | // checks that the order has not been executed | modifier onlyOrderMatchingEngine() {
// address(0) allowed to by pass this check in order to perform eth_call simulations
require(
// it's a simulation
msg.sender == address(0)
// or the sender is an authorized order matching engine
|| orderMatchingEngine[msg.sender],
"Only OME"
);
_;
}
| modifier onlyOrderMatchingEngine() {
// address(0) allowed to by pass this check in order to perform eth_call simulations
require(
// it's a simulation
msg.sender == address(0)
// or the sender is an authorized order matching engine
|| orderMatchingEngine[msg.sender],
"Only OME"
);
_;
}
| 29,609 |
16 | // Upgradeable Conract contract that implements doubly linked list to keep track of old and new versions of this contract / | contract Upgradeable is Ownable{
address public lastContract;
address public nextContract;
bool public isOldVersion;
bool public allowedToUpgrade;
/**
* @dev makes contract upgradeable
*/
function Upgradeable() public {
allowedToUpgrade = true;
}
/**
* @dev signals that new upgrade is available, contract must be most recent
* upgrade and allowed to upgrade
* @param newContract Address of upgraded contract
*/
function upgradeTo(Upgradeable newContract) public ownerOnly{
require(allowedToUpgrade && !isOldVersion);
nextContract = newContract;
isOldVersion = true;
newContract.confirmUpgrade();
}
/**
* @dev confirmation that this is indeed the next version,
* called from previous version of contract. Anyone can call this function,
* which basically makes this instance unusable if that happens. Once called,
* this contract can not serve as upgrade to another contract. Not an ideal solution
* but will work until we have a more sophisticated approach using a dispatcher or similar
*/
function confirmUpgrade() public {
require(lastContract == address(0));
lastContract = msg.sender;
}
}
| contract Upgradeable is Ownable{
address public lastContract;
address public nextContract;
bool public isOldVersion;
bool public allowedToUpgrade;
/**
* @dev makes contract upgradeable
*/
function Upgradeable() public {
allowedToUpgrade = true;
}
/**
* @dev signals that new upgrade is available, contract must be most recent
* upgrade and allowed to upgrade
* @param newContract Address of upgraded contract
*/
function upgradeTo(Upgradeable newContract) public ownerOnly{
require(allowedToUpgrade && !isOldVersion);
nextContract = newContract;
isOldVersion = true;
newContract.confirmUpgrade();
}
/**
* @dev confirmation that this is indeed the next version,
* called from previous version of contract. Anyone can call this function,
* which basically makes this instance unusable if that happens. Once called,
* this contract can not serve as upgrade to another contract. Not an ideal solution
* but will work until we have a more sophisticated approach using a dispatcher or similar
*/
function confirmUpgrade() public {
require(lastContract == address(0));
lastContract = msg.sender;
}
}
| 25,196 |
47 | // Used to store the minimum bid required to outbid the highest bidder | uint256 minValidBid;
| uint256 minValidBid;
| 71,386 |
1 | // EIP-20 token symbol for this token | string public constant symbol = "CTX";
| string public constant symbol = "CTX";
| 3,429 |
184 | // Check if expired round has a balance | if (expired.balance > expired.claimed) {
| if (expired.balance > expired.claimed) {
| 44,776 |
36 | // Implementation of IVote interface. Majority_Judgment_Ballot contract implement the Majority Judgment which is a ballot process proven to be able to avoid biases of classical Uninominal ballot such as strategic vote. In Majority Judgment ballot, citizens assess each candidat and give it a grade. In our implementation, each candidat proposition can be assessed as «Reject», «Bad», «Neutral», «Good» and «Excelent». For each candidat proposition, citizens assessment are sorted from best grades to worst ones (from «Excelent» to «Reject»). The majority grade of a proposition corresponds to it’s median grade. If the majority grade of a candidat proposition is «Good», it means | contract Majority_Judgment_Ballot is IVote{
enum Assessement{
EXCELENT,
GOOD,
NEUTRAL,
BAD,
REJECT
}
enum Ballot_Status{
NON_CREATED,
VOTE,
VOTE_VALIDATION,
FINISHED
}
struct Voter{
bool Voted;
bool Validated;
bytes32 Choice;
}
struct Propositions_Result{
uint[5] Cumulated_Score;
Assessement Median_Grade;
}
struct Ballot{
address Voters_Register_Address;
bytes4 Check_Voter_Selector;
Ballot_Status Status;
uint Creation_Timestamp;
uint End_Vote_Timestamp;
uint Vote_Duration;
uint Vote_Validation_Duration;
uint Propositions_Number;
uint Max_Winning_Propositions_Number;
uint Voter_Number;
uint[] Winning_Propositions;
mapping(address=>Voter) Voters;
mapping(uint=>Propositions_Result) Propositions_Results; //From 0 to Propositions_Number. If the 0 proposition get the first place, the oder propositions are rejected.
}
event Ballot_Created(bytes32 key);
event Voted_Clear(bytes32 key, address voter);
event Voted_Hashed(bytes32 key, address voter);
event Begin_Validation(bytes32 key);
event Validated_Vote(bytes32 key, address voter);
event Vote_Finished(bytes32 key);
/// @dev Mapping of all voting sessions of the contract.
mapping(bytes32=>Ballot) public Ballots;
/// @dev See {IVote} interface.
function Create_Ballot(bytes32 key, address Voters_Register_Address, bytes4 Check_Voter_Selector, uint Vote_Duration, uint Vote_Validation_Duration, uint Propositions_Number, uint Max_Winning_Propositions_Number) external override {
require(Ballots[key].Creation_Timestamp == 0, "Already Existing Ballot");
if(Voters_Register_Address==address(0) || Check_Voter_Selector==bytes4(0) || Vote_Duration==0 || Max_Winning_Propositions_Number==0 ){
revert("Bad Argument Values");
}
if(Propositions_Number==1){
require(Max_Winning_Propositions_Number==1, "Argument Inconsistency");
}else{
require(Propositions_Number>Max_Winning_Propositions_Number, "Argument Inconsistency");
}
Ballots[key].Voters_Register_Address =Voters_Register_Address;
Ballots[key].Check_Voter_Selector = Check_Voter_Selector;
Ballots[key].Vote_Duration = Vote_Duration;
Ballots[key].Vote_Validation_Duration = Vote_Validation_Duration;
Ballots[key].Propositions_Number = Propositions_Number;
Ballots[key].Max_Winning_Propositions_Number = Max_Winning_Propositions_Number;
Ballots[key].Creation_Timestamp =block.timestamp;
Ballots[key].Status = Ballot_Status.VOTE;
emit Ballot_Created(key);
}
/// @dev See {IVote} interface.
function Vote_Clear(bytes32 key, uint[] calldata Choices) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration == 0, "Should Use Vote_Hashed");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number + 1 == choice_len, "Choices argument wrong size");
Ballots[key].Voter_Number = Ballots[key].Voter_Number +1;
Ballots[key].Voters[msg.sender].Voted = true;
for(uint i=0; i< choice_len; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Voted_Clear(key, msg.sender);
}
/// @dev See {IVote} interface.
function Vote_Hashed(bytes32 key, bytes32 Hash) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration > 0, "Should Use Vote_Clear");
Ballots[key].Voters[msg.sender].Voted = true;
Ballots[key].Voters[msg.sender].Choice = Hash;
emit Voted_Hashed( key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Vote(bytes32 key)external override{
require(Ballots[key].Status==Ballot_Status.VOTE, "Not at voting stage");
require(Ballots[key].Vote_Duration < block.timestamp - Ballots[key].Creation_Timestamp, "Voting stage not finished");
if(Ballots[key].Vote_Validation_Duration>0){
Ballots[key].Status = Ballot_Status.VOTE_VALIDATION;
emit Begin_Validation(key);
}else{
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
Ballots[key].End_Vote_Timestamp = block.timestamp;
}
/// @dev See {IVote} interface.
function Valdiate_Vote(bytes32 key, uint[] calldata Choices, bytes32 salt )external override {
require(Ballots[key].Status==Ballot_Status.VOTE_VALIDATION, "Not at vote validation stage");
require(!Ballots[key].Voters[msg.sender].Validated, "Vote Already Validated");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number+1 == choice_len, "Choices argument wrong size");
bytes32 hash = keccak256(abi.encode(Choices, salt));
require(hash==Ballots[key].Voters[msg.sender].Choice, "Hashes don't match");
Ballots[key].Voters[msg.sender].Validated = true;
Ballots[key].Voter_Number = Ballots[key].Voter_Number+1;
for(uint i=0; i<Choices.length; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Validated_Vote(key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Validation_Vote(bytes32 key) external override{
require( (Ballots[key].Status == Ballot_Status.VOTE_VALIDATION && Ballots[key].Vote_Validation_Duration < block.timestamp - Ballots[key].End_Vote_Timestamp), "Not at vote counting stage");
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
/**
* @dev Count votes.
* @param key Id of the voting session
*/
function _Talling_Votes(bytes32 key) internal{
uint number_propositions = Ballots[key].Propositions_Number;
uint half_voters = Ballots[key].Voter_Number/2 + Ballots[key].Voter_Number%2;
uint winning_propositions_number = Ballots[key].Max_Winning_Propositions_Number;
uint[] memory winning_propositions = new uint[](winning_propositions_number+1);
uint[] memory winning_propositions_grades = new uint[](winning_propositions_number+1);
uint mention;
uint rank;
uint winning_list_size;
bool continu;
uint Temp_prop;
//Assessement of eaxh proposition
for(uint prop=0; prop<=number_propositions; prop++){
while(Ballots[key].Propositions_Results[prop].Cumulated_Score[mention]<half_voters){
mention++;
}
Ballots[key].Propositions_Results[prop].Median_Grade = Assessement(mention);
//Fetching the "winning_propositions_number" winning propositions.
continu=true;
while(continu && rank<winning_list_size){
if(winning_propositions_grades[rank]<mention || (winning_propositions_grades[rank]==mention && Order_Proposition_Result(key, winning_propositions[rank], prop, mention)!=prop)){
rank++;
}else{
continu=false;
}
}
if(winning_list_size<winning_propositions_number+1){
winning_list_size++;
}
Temp_prop=prop;
while(rank<winning_list_size){
if(rank+1<winning_list_size){
(winning_propositions[rank], Temp_prop) = (Temp_prop, winning_propositions[rank]);
(winning_propositions_grades[rank], mention) = (mention, winning_propositions_grades[rank]);
rank++;
}else{
winning_propositions[rank]=Temp_prop;
winning_propositions_grades[rank]=mention;
rank = winning_list_size;
}
}
rank=0;
mention=0;
}
if(winning_propositions[0]==0){ //If the first proposition is the default proposition
Ballots[key].Winning_Propositions.push(0);
}else{
uint i;
while(Ballots[key].Winning_Propositions.length<winning_propositions_number){
if(winning_propositions[i]!=0){ //0 proposition is conssidered only if it is in the first position
Ballots[key].Winning_Propositions.push(winning_propositions[i]);
}
i++;
}
}
}
/**
* @dev Sort by their score two propositions that have the same {median_grade}. The function returns the id of the most popular function.
* @param key Id of the voting session
* @param prop1 First proposition Id.
* @param prop2 Second proposition Id.
* @param median_grade Median grade score.
*
*/
function Order_Proposition_Result(bytes32 key, uint prop1, uint prop2, uint median_grade)internal view returns(uint){
if(median_grade==0){
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[0]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[0])? prop2:prop1;
}else{
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[median_grade-1]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[median_grade-1])? prop2:prop1;
}
}
/**
* @dev Check whether an account is registered in the {Voters_Register_Address} contract. In other words, it checks whether the account has the right to vote in the voting session or not.
* @param key Id of the voting session
* @param voter_address Address of the account.
*
*/
function Check_Voter_Address(bytes32 key, address voter_address) internal returns(bool){
(bool success, bytes memory Data) = Ballots[key].Voters_Register_Address.call(abi.encodeWithSelector(Ballots[key].Check_Voter_Selector, voter_address));
require(success, "Voter check function reverted");
return abi.decode(Data, (bool));
}
/*GETTER*/
/// @dev See {IVote} interface
function Get_Winning_Propositions(bytes32 key)external view override returns(uint[] memory Winning_Propositions_List){
require(Ballots[key].Status == Ballot_Status.FINISHED, "Ballot still Pending");
return Ballots[key].Winning_Propositions;
}
/// @dev See {IVote} interface
function Get_Winning_Proposition_byId(bytes32 key, uint Id)external view override returns(uint Winning_Proposition){
require(Id<Ballots[key].Winning_Propositions.length, "Id exceed Winning length");
return Ballots[key].Winning_Propositions[Id];
}
/// @dev See {IVote} interface
function HasVoted(bytes32 key, address voter_address) external view override returns(bool hasvoted){
return Ballots[key].Voters[voter_address].Voted;
}
/// @dev See {IVote} interface
function HasValidated(bytes32 key, address voter_address) external view override returns(bool Validated, bytes32 Choice){
return (Ballots[key].Voters[voter_address].Validated, Ballots[key].Voters[voter_address].Choice);
}
/// @dev See {IVote} interface
function Get_Voter_Number(bytes32 key)external view override returns(uint voter_num){
return Ballots[key].Voter_Number;
}
/**
* @dev Get the score obtained by a proposition
* @param key Id of the voting session
* @param proposition_Id Index of the proposition
* @return proposition_result
*
* */
function Get_Propositions_Result(bytes32 key, uint proposition_Id) external view returns(Propositions_Result memory proposition_result){
return Ballots[key].Propositions_Results[proposition_Id];
}
}
| contract Majority_Judgment_Ballot is IVote{
enum Assessement{
EXCELENT,
GOOD,
NEUTRAL,
BAD,
REJECT
}
enum Ballot_Status{
NON_CREATED,
VOTE,
VOTE_VALIDATION,
FINISHED
}
struct Voter{
bool Voted;
bool Validated;
bytes32 Choice;
}
struct Propositions_Result{
uint[5] Cumulated_Score;
Assessement Median_Grade;
}
struct Ballot{
address Voters_Register_Address;
bytes4 Check_Voter_Selector;
Ballot_Status Status;
uint Creation_Timestamp;
uint End_Vote_Timestamp;
uint Vote_Duration;
uint Vote_Validation_Duration;
uint Propositions_Number;
uint Max_Winning_Propositions_Number;
uint Voter_Number;
uint[] Winning_Propositions;
mapping(address=>Voter) Voters;
mapping(uint=>Propositions_Result) Propositions_Results; //From 0 to Propositions_Number. If the 0 proposition get the first place, the oder propositions are rejected.
}
event Ballot_Created(bytes32 key);
event Voted_Clear(bytes32 key, address voter);
event Voted_Hashed(bytes32 key, address voter);
event Begin_Validation(bytes32 key);
event Validated_Vote(bytes32 key, address voter);
event Vote_Finished(bytes32 key);
/// @dev Mapping of all voting sessions of the contract.
mapping(bytes32=>Ballot) public Ballots;
/// @dev See {IVote} interface.
function Create_Ballot(bytes32 key, address Voters_Register_Address, bytes4 Check_Voter_Selector, uint Vote_Duration, uint Vote_Validation_Duration, uint Propositions_Number, uint Max_Winning_Propositions_Number) external override {
require(Ballots[key].Creation_Timestamp == 0, "Already Existing Ballot");
if(Voters_Register_Address==address(0) || Check_Voter_Selector==bytes4(0) || Vote_Duration==0 || Max_Winning_Propositions_Number==0 ){
revert("Bad Argument Values");
}
if(Propositions_Number==1){
require(Max_Winning_Propositions_Number==1, "Argument Inconsistency");
}else{
require(Propositions_Number>Max_Winning_Propositions_Number, "Argument Inconsistency");
}
Ballots[key].Voters_Register_Address =Voters_Register_Address;
Ballots[key].Check_Voter_Selector = Check_Voter_Selector;
Ballots[key].Vote_Duration = Vote_Duration;
Ballots[key].Vote_Validation_Duration = Vote_Validation_Duration;
Ballots[key].Propositions_Number = Propositions_Number;
Ballots[key].Max_Winning_Propositions_Number = Max_Winning_Propositions_Number;
Ballots[key].Creation_Timestamp =block.timestamp;
Ballots[key].Status = Ballot_Status.VOTE;
emit Ballot_Created(key);
}
/// @dev See {IVote} interface.
function Vote_Clear(bytes32 key, uint[] calldata Choices) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration == 0, "Should Use Vote_Hashed");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number + 1 == choice_len, "Choices argument wrong size");
Ballots[key].Voter_Number = Ballots[key].Voter_Number +1;
Ballots[key].Voters[msg.sender].Voted = true;
for(uint i=0; i< choice_len; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Voted_Clear(key, msg.sender);
}
/// @dev See {IVote} interface.
function Vote_Hashed(bytes32 key, bytes32 Hash) external override{
require(Ballots[key].Status == Ballot_Status.VOTE, "Not at voting stage");
require(!Ballots[key].Voters[msg.sender].Voted, "Already Voted");
require(Check_Voter_Address(key, msg.sender), "Address Not Allowed");
require(Ballots[key].Vote_Validation_Duration > 0, "Should Use Vote_Clear");
Ballots[key].Voters[msg.sender].Voted = true;
Ballots[key].Voters[msg.sender].Choice = Hash;
emit Voted_Hashed( key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Vote(bytes32 key)external override{
require(Ballots[key].Status==Ballot_Status.VOTE, "Not at voting stage");
require(Ballots[key].Vote_Duration < block.timestamp - Ballots[key].Creation_Timestamp, "Voting stage not finished");
if(Ballots[key].Vote_Validation_Duration>0){
Ballots[key].Status = Ballot_Status.VOTE_VALIDATION;
emit Begin_Validation(key);
}else{
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
Ballots[key].End_Vote_Timestamp = block.timestamp;
}
/// @dev See {IVote} interface.
function Valdiate_Vote(bytes32 key, uint[] calldata Choices, bytes32 salt )external override {
require(Ballots[key].Status==Ballot_Status.VOTE_VALIDATION, "Not at vote validation stage");
require(!Ballots[key].Voters[msg.sender].Validated, "Vote Already Validated");
uint choice_len = Choices.length ;
require(Ballots[key].Propositions_Number+1 == choice_len, "Choices argument wrong size");
bytes32 hash = keccak256(abi.encode(Choices, salt));
require(hash==Ballots[key].Voters[msg.sender].Choice, "Hashes don't match");
Ballots[key].Voters[msg.sender].Validated = true;
Ballots[key].Voter_Number = Ballots[key].Voter_Number+1;
for(uint i=0; i<Choices.length; i++){
for(uint j=Choices[i]; j<5; j++){
Ballots[key].Propositions_Results[i].Cumulated_Score[j]++;
}
}
emit Validated_Vote(key, msg.sender);
}
/// @dev See {IVote} interface.
function End_Validation_Vote(bytes32 key) external override{
require( (Ballots[key].Status == Ballot_Status.VOTE_VALIDATION && Ballots[key].Vote_Validation_Duration < block.timestamp - Ballots[key].End_Vote_Timestamp), "Not at vote counting stage");
_Talling_Votes(key);
Ballots[key].Status = Ballot_Status.FINISHED;
emit Vote_Finished(key);
}
/**
* @dev Count votes.
* @param key Id of the voting session
*/
function _Talling_Votes(bytes32 key) internal{
uint number_propositions = Ballots[key].Propositions_Number;
uint half_voters = Ballots[key].Voter_Number/2 + Ballots[key].Voter_Number%2;
uint winning_propositions_number = Ballots[key].Max_Winning_Propositions_Number;
uint[] memory winning_propositions = new uint[](winning_propositions_number+1);
uint[] memory winning_propositions_grades = new uint[](winning_propositions_number+1);
uint mention;
uint rank;
uint winning_list_size;
bool continu;
uint Temp_prop;
//Assessement of eaxh proposition
for(uint prop=0; prop<=number_propositions; prop++){
while(Ballots[key].Propositions_Results[prop].Cumulated_Score[mention]<half_voters){
mention++;
}
Ballots[key].Propositions_Results[prop].Median_Grade = Assessement(mention);
//Fetching the "winning_propositions_number" winning propositions.
continu=true;
while(continu && rank<winning_list_size){
if(winning_propositions_grades[rank]<mention || (winning_propositions_grades[rank]==mention && Order_Proposition_Result(key, winning_propositions[rank], prop, mention)!=prop)){
rank++;
}else{
continu=false;
}
}
if(winning_list_size<winning_propositions_number+1){
winning_list_size++;
}
Temp_prop=prop;
while(rank<winning_list_size){
if(rank+1<winning_list_size){
(winning_propositions[rank], Temp_prop) = (Temp_prop, winning_propositions[rank]);
(winning_propositions_grades[rank], mention) = (mention, winning_propositions_grades[rank]);
rank++;
}else{
winning_propositions[rank]=Temp_prop;
winning_propositions_grades[rank]=mention;
rank = winning_list_size;
}
}
rank=0;
mention=0;
}
if(winning_propositions[0]==0){ //If the first proposition is the default proposition
Ballots[key].Winning_Propositions.push(0);
}else{
uint i;
while(Ballots[key].Winning_Propositions.length<winning_propositions_number){
if(winning_propositions[i]!=0){ //0 proposition is conssidered only if it is in the first position
Ballots[key].Winning_Propositions.push(winning_propositions[i]);
}
i++;
}
}
}
/**
* @dev Sort by their score two propositions that have the same {median_grade}. The function returns the id of the most popular function.
* @param key Id of the voting session
* @param prop1 First proposition Id.
* @param prop2 Second proposition Id.
* @param median_grade Median grade score.
*
*/
function Order_Proposition_Result(bytes32 key, uint prop1, uint prop2, uint median_grade)internal view returns(uint){
if(median_grade==0){
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[0]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[0])? prop2:prop1;
}else{
return (Ballots[key].Propositions_Results[prop1].Cumulated_Score[median_grade-1]<Ballots[key].Propositions_Results[prop2].Cumulated_Score[median_grade-1])? prop2:prop1;
}
}
/**
* @dev Check whether an account is registered in the {Voters_Register_Address} contract. In other words, it checks whether the account has the right to vote in the voting session or not.
* @param key Id of the voting session
* @param voter_address Address of the account.
*
*/
function Check_Voter_Address(bytes32 key, address voter_address) internal returns(bool){
(bool success, bytes memory Data) = Ballots[key].Voters_Register_Address.call(abi.encodeWithSelector(Ballots[key].Check_Voter_Selector, voter_address));
require(success, "Voter check function reverted");
return abi.decode(Data, (bool));
}
/*GETTER*/
/// @dev See {IVote} interface
function Get_Winning_Propositions(bytes32 key)external view override returns(uint[] memory Winning_Propositions_List){
require(Ballots[key].Status == Ballot_Status.FINISHED, "Ballot still Pending");
return Ballots[key].Winning_Propositions;
}
/// @dev See {IVote} interface
function Get_Winning_Proposition_byId(bytes32 key, uint Id)external view override returns(uint Winning_Proposition){
require(Id<Ballots[key].Winning_Propositions.length, "Id exceed Winning length");
return Ballots[key].Winning_Propositions[Id];
}
/// @dev See {IVote} interface
function HasVoted(bytes32 key, address voter_address) external view override returns(bool hasvoted){
return Ballots[key].Voters[voter_address].Voted;
}
/// @dev See {IVote} interface
function HasValidated(bytes32 key, address voter_address) external view override returns(bool Validated, bytes32 Choice){
return (Ballots[key].Voters[voter_address].Validated, Ballots[key].Voters[voter_address].Choice);
}
/// @dev See {IVote} interface
function Get_Voter_Number(bytes32 key)external view override returns(uint voter_num){
return Ballots[key].Voter_Number;
}
/**
* @dev Get the score obtained by a proposition
* @param key Id of the voting session
* @param proposition_Id Index of the proposition
* @return proposition_result
*
* */
function Get_Propositions_Result(bytes32 key, uint proposition_Id) external view returns(Propositions_Result memory proposition_result){
return Ballots[key].Propositions_Results[proposition_Id];
}
}
| 33,344 |
21 | // Validate token balance | require (virtuePlayerPoints.balanceOf(this) == MAX_TOKENS_SOLD);
stage = Stages.AuctionSetUp;
| require (virtuePlayerPoints.balanceOf(this) == MAX_TOKENS_SOLD);
stage = Stages.AuctionSetUp;
| 5,161 |
112 | // buyback MM and notify MasterChef | function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal {
if (buybackEnabled == true && _buybackAmount > 0) {
_swapUniswap(_buybackPrinciple, mmToken, _buybackAmount);
uint256 _mmBought = IERC20(mmToken).balanceOf(address(this));
IERC20(mmToken).safeTransfer(masterChef, _mmBought);
IMasterchef(masterChef).notifyBuybackReward(_mmBought);
}
}
| function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal {
if (buybackEnabled == true && _buybackAmount > 0) {
_swapUniswap(_buybackPrinciple, mmToken, _buybackAmount);
uint256 _mmBought = IERC20(mmToken).balanceOf(address(this));
IERC20(mmToken).safeTransfer(masterChef, _mmBought);
IMasterchef(masterChef).notifyBuybackReward(_mmBought);
}
}
| 14,019 |
33 | // do not allow to drain core token (Amount or lps) before pool ends | require(_token != token, "token");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "pool.lpToken");
}
| require(_token != token, "token");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "pool.lpToken");
}
| 33,467 |
4 | // token.burn(msg.sender, amount);instead of burning transfer to admin account | uint AmountwithFees = amount + fees;
token.transferFrom(to, address(this), AmountwithFees);
emit Transfer(
msg.sender,
to,
amount,
block.timestamp,
nonce,
| uint AmountwithFees = amount + fees;
token.transferFrom(to, address(this), AmountwithFees);
emit Transfer(
msg.sender,
to,
amount,
block.timestamp,
nonce,
| 12,470 |
304 | // get user unrealized PNL / | function getUserUnrealizedPNL() public view override returns (Decimal.decimal memory, Decimal.decimal memory) {
Decimal.decimal memory _baseAssetReserve = baseAssetReserve;
Decimal.decimal memory _quoteAssetReserve = quoteAssetReserve;
Decimal.decimal memory invariant = _baseAssetReserve.mulD(_quoteAssetReserve);
// close all long position
Decimal.decimal memory unrealizedLongQuoteAssetAmout =
getOutputPriceWithReserves(Dir.ADD_TO_AMM, longPositionSize, _quoteAssetReserve, _baseAssetReserve);
_baseAssetReserve = _baseAssetReserve.addD(longPositionSize);
_quoteAssetReserve = invariant.divD(_baseAssetReserve);
// close all short position
Decimal.decimal memory unrealizedShortQuoteAssetAmout =
getOutputPriceWithReserves(Dir.REMOVE_FROM_AMM, shortPositionSize, _quoteAssetReserve, _baseAssetReserve);
return (unrealizedLongQuoteAssetAmout, unrealizedShortQuoteAssetAmout);
}
| function getUserUnrealizedPNL() public view override returns (Decimal.decimal memory, Decimal.decimal memory) {
Decimal.decimal memory _baseAssetReserve = baseAssetReserve;
Decimal.decimal memory _quoteAssetReserve = quoteAssetReserve;
Decimal.decimal memory invariant = _baseAssetReserve.mulD(_quoteAssetReserve);
// close all long position
Decimal.decimal memory unrealizedLongQuoteAssetAmout =
getOutputPriceWithReserves(Dir.ADD_TO_AMM, longPositionSize, _quoteAssetReserve, _baseAssetReserve);
_baseAssetReserve = _baseAssetReserve.addD(longPositionSize);
_quoteAssetReserve = invariant.divD(_baseAssetReserve);
// close all short position
Decimal.decimal memory unrealizedShortQuoteAssetAmout =
getOutputPriceWithReserves(Dir.REMOVE_FROM_AMM, shortPositionSize, _quoteAssetReserve, _baseAssetReserve);
return (unrealizedLongQuoteAssetAmout, unrealizedShortQuoteAssetAmout);
}
| 15,903 |
53 | // If `amount` is 0, or `from` is `to` nothing happens | if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
| if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
| 20,890 |
19 | // User Interaction Functions / user join the current game round | function joinRound(uint256 _position) external payable nonReentrant override returns (bool) {
RoundInfo storage round = rounds[currentRoundID];
PlayerInfo storage player = players[msg.sender];
require(address(msg.sender).balance > 2 ether);
require(round.status == 1, "only can deposit in open time");
require(round.initTime <= block.timestamp && round.initTime + openDuration >= block.timestamp, "only in open window");
require(_position >= 1 && _position <= 3, "position within a range");
// transfer 10 matic to the contract
(bool success, ) = payable(address(this)).call{value: 2 ether}(" ");
if (!success) {
revert CallFailed();
}
// setting the player info
player.position[currentRoundID] = _position;
// setting the round info
if (_position == 1) {
round.totalLongAmount += 2;
}
if (_position == 2) {
round.totalShortAmount += 2;
}
if (_position == 3) {
round.totalTieAmount += 2;
}
return true;
}
| function joinRound(uint256 _position) external payable nonReentrant override returns (bool) {
RoundInfo storage round = rounds[currentRoundID];
PlayerInfo storage player = players[msg.sender];
require(address(msg.sender).balance > 2 ether);
require(round.status == 1, "only can deposit in open time");
require(round.initTime <= block.timestamp && round.initTime + openDuration >= block.timestamp, "only in open window");
require(_position >= 1 && _position <= 3, "position within a range");
// transfer 10 matic to the contract
(bool success, ) = payable(address(this)).call{value: 2 ether}(" ");
if (!success) {
revert CallFailed();
}
// setting the player info
player.position[currentRoundID] = _position;
// setting the round info
if (_position == 1) {
round.totalLongAmount += 2;
}
if (_position == 2) {
round.totalShortAmount += 2;
}
if (_position == 3) {
round.totalTieAmount += 2;
}
return true;
}
| 19,950 |
151 | // Mapping of shares that are reserved for payout | mapping(address => uint256) private toBePaid;
| mapping(address => uint256) private toBePaid;
| 16,533 |
3 | // Amount dedicated to the dao (13M - 5M) | uint256 public constant DAO_QUOTA = 8_000_000 * DEFAULT_FACTOR;
| uint256 public constant DAO_QUOTA = 8_000_000 * DEFAULT_FACTOR;
| 20,557 |
107 | // AA apr is: stratAprAAaprSplitRatio / AASplitRatio | stratApr * _trancheAPRSplitRatio / _AATrancheSplitRatio :
| stratApr * _trancheAPRSplitRatio / _AATrancheSplitRatio :
| 33,368 |
19 | // register indexes (coinA pos in coinB array, coinB pos in coinA array) | if (_coinA < _coinB) {
coinSwapIndexes[_key] = (coinAPos << 128) + coinBPos;
} else {
| if (_coinA < _coinB) {
coinSwapIndexes[_key] = (coinAPos << 128) + coinBPos;
} else {
| 18,486 |
27 | // ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- | contract GOGOLCOIN is IERC20, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() {
symbol = "GOL";
name = "GOGOLCOIN";
decimals = 4;
_totalSupply = 295000000 * (10 ** decimals);
address owner = 0x17e0c9168ce75f8636b6B65982B400b32ef4452b;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view override returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public virtual override returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public virtual override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view virtual override returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
receive () external payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return IERC20(tokenAddress).transfer(owner, tokens);
}
} | contract GOGOLCOIN is IERC20, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() {
symbol = "GOL";
name = "GOGOLCOIN";
decimals = 4;
_totalSupply = 295000000 * (10 ** decimals);
address owner = 0x17e0c9168ce75f8636b6B65982B400b32ef4452b;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view override returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public virtual override returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public virtual override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view virtual override returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
receive () external payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return IERC20(tokenAddress).transfer(owner, tokens);
}
} | 29,492 |
49 | // swap and liquify | distributeAndLiquify(from, to);
| distributeAndLiquify(from, to);
| 1,941 |
49 | // Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. _spender The address which will spend the funds. _value The amount of tokens to be spent. / | function approve(address _spender, uint256 _value) public allowTransfer(_spender) returns (bool) {
return super.approve(_spender, _value);
}
| function approve(address _spender, uint256 _value) public allowTransfer(_spender) returns (bool) {
return super.approve(_spender, _value);
}
| 39,444 |
8 | // Function that gets the img and text hashes _index number from total post iteration returns stored images and text hashes | function getHash(uint256 _index)
public view returns (string memory img, string memory text, address owner)
| function getHash(uint256 _index)
public view returns (string memory img, string memory text, address owner)
| 18,862 |
61 | // if not Ethereum | if (address(cSrcToken) != kETH) {
| if (address(cSrcToken) != kETH) {
| 54,392 |
25 | // Returns a concatenation of seven bytes. b1 The first bytes to be concatenated.... b7 The last bytes to be concatenated. / | function concatBytes(bytes b1, bytes b2, bytes b3, bytes b4, bytes b5, bytes b6, bytes b7) internal returns (bytes bFinal) {
bFinal = new bytes(b1.length + b2.length + b3.length + b4.length + b5.length + b6.length + b7.length);
uint i = 0;
uint j;
for (j = 0; j < b1.length; j++) bFinal[i++] = b1[j];
for (j = 0; j < b2.length; j++) bFinal[i++] = b2[j];
for (j = 0; j < b3.length; j++) bFinal[i++] = b3[j];
for (j = 0; j < b4.length; j++) bFinal[i++] = b4[j];
for (j = 0; j < b5.length; j++) bFinal[i++] = b5[j];
for (j = 0; j < b6.length; j++) bFinal[i++] = b6[j];
for (j = 0; j < b7.length; j++) bFinal[i++] = b7[j];
}
| function concatBytes(bytes b1, bytes b2, bytes b3, bytes b4, bytes b5, bytes b6, bytes b7) internal returns (bytes bFinal) {
bFinal = new bytes(b1.length + b2.length + b3.length + b4.length + b5.length + b6.length + b7.length);
uint i = 0;
uint j;
for (j = 0; j < b1.length; j++) bFinal[i++] = b1[j];
for (j = 0; j < b2.length; j++) bFinal[i++] = b2[j];
for (j = 0; j < b3.length; j++) bFinal[i++] = b3[j];
for (j = 0; j < b4.length; j++) bFinal[i++] = b4[j];
for (j = 0; j < b5.length; j++) bFinal[i++] = b5[j];
for (j = 0; j < b6.length; j++) bFinal[i++] = b6[j];
for (j = 0; j < b7.length; j++) bFinal[i++] = b7[j];
}
| 43,237 |
2 | // ovl token | IOverlayV1Token public immutable ovl;
| IOverlayV1Token public immutable ovl;
| 35,240 |
13 | // Wrapping is only possible when there is already a listing, you are buying your own listing and therefore getting your eth back in your wallet.Only Owner can do a mint of a wrapper, or 0x0 (unowned tiles) / | function wrap(uint _locationID) external payable {
require(!_exists(_locationID), "PixelMapWrapper: You cannot mint the same locationID");
require(getwithdrawableETHforLocation(_locationID) == 0, "PixelMapWrapper: There is still ETH to be withdrawn");
// get Tile from contract
(address _owner,,,uint _price) = _pixelmap.getTile(_locationID);
// check owner
require(_owner == _msgSender() || _owner == address(0), "PixelMapWrapper: You are not the owner or it");
require(_price == msg.value, "PixelMapWrapper: Price not identical");
// Buy Offering with this contract
_pixelmap.buyTile{value: msg.value}(_locationID);
// Check Tile if correct transfered
(address _newowner,,, uint _newprice) = _pixelmap.getTile(_locationID);
require(_newprice == 0 && _newowner == address(this), "PixelMapWrapper: Price or Owner not Updated");
// Mint ERC721 NFT
_mint(msg.sender, _locationID);
emit Wrapped(msg.sender, _locationID);
}
| function wrap(uint _locationID) external payable {
require(!_exists(_locationID), "PixelMapWrapper: You cannot mint the same locationID");
require(getwithdrawableETHforLocation(_locationID) == 0, "PixelMapWrapper: There is still ETH to be withdrawn");
// get Tile from contract
(address _owner,,,uint _price) = _pixelmap.getTile(_locationID);
// check owner
require(_owner == _msgSender() || _owner == address(0), "PixelMapWrapper: You are not the owner or it");
require(_price == msg.value, "PixelMapWrapper: Price not identical");
// Buy Offering with this contract
_pixelmap.buyTile{value: msg.value}(_locationID);
// Check Tile if correct transfered
(address _newowner,,, uint _newprice) = _pixelmap.getTile(_locationID);
require(_newprice == 0 && _newowner == address(this), "PixelMapWrapper: Price or Owner not Updated");
// Mint ERC721 NFT
_mint(msg.sender, _locationID);
emit Wrapped(msg.sender, _locationID);
}
| 31,623 |
251 | // You can set these parameters on deployment to whatever you want | maxReportDelay = 86400; // once per 24 hours
profitFactor = 100; // multiple before triggering harvest
_setMarketIdFromTokenAddress();
| maxReportDelay = 86400; // once per 24 hours
profitFactor = 100; // multiple before triggering harvest
_setMarketIdFromTokenAddress();
| 5,062 |
9 | // The number of this shares this debtor is allocated of the base interest. | uint128 baseShares;
| uint128 baseShares;
| 35,637 |
4 | // Get expected unlock time if try to stake 'amount' tokens. | function calcUnlockTime(address account, uint256 amount) public view returns (uint256) {
return _calcUnlockTime(stakedBalances[account], amount);
}
| function calcUnlockTime(address account, uint256 amount) public view returns (uint256) {
return _calcUnlockTime(stakedBalances[account], amount);
}
| 45,734 |
27 | // IConstantFlowAgreementV1.getAccountFlowInfo implementation | function getAccountFlowInfo(
ISuperfluidToken token,
address account
)
external view override
returns (
uint256 timestamp,
int96 flowRate,
uint256 deposit,
uint256 owedDeposit)
| function getAccountFlowInfo(
ISuperfluidToken token,
address account
)
external view override
returns (
uint256 timestamp,
int96 flowRate,
uint256 deposit,
uint256 owedDeposit)
| 10,487 |
258 | // Only fall back when the sender is not the admin. / | function _willFallback() internal override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
| function _willFallback() internal override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
| 2,463 |
9 | // Next entry starts at 85 byte + data length | i := add(i, add(0x55, dataLength))
| i := add(i, add(0x55, dataLength))
| 21,612 |
508 | // Checks if the collateral token has been added to the position manager, or reverts otherwise./collateralToken The collateral token to check. | modifier collateralTokenExists(IERC20 collateralToken) {
if (address(collateralInfo[collateralToken].collateralToken) == address(0)) {
revert CollateralTokenNotAdded();
}
_;
}
| modifier collateralTokenExists(IERC20 collateralToken) {
if (address(collateralInfo[collateralToken].collateralToken) == address(0)) {
revert CollateralTokenNotAdded();
}
_;
}
| 6,165 |
248 | // List of supporters for each active bid proposal | mapping (uint256 => mapping (address => bool)) BidProposalSupporters;
| mapping (uint256 => mapping (address => bool)) BidProposalSupporters;
| 25,433 |
687 | // rebuild the caches of mixin smart contracts/destinations The list of mixinOperatorResolver to rebuild | function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner {
for (uint256 i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
| function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner {
for (uint256 i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
| 60,336 |
24 | // Collect stkAAVE | function aaveCollect_stkAAVE() public onlyByOwnGovCust {
address[] memory the_assets = new address[](1);
the_assets[0] = address(aaveUSDC_Token);
uint256 rewards_balance = AAVEIncentivesController.getRewardsBalance(the_assets, address(this));
AAVEIncentivesController.claimRewards(the_assets, rewards_balance, address(this));
}
| function aaveCollect_stkAAVE() public onlyByOwnGovCust {
address[] memory the_assets = new address[](1);
the_assets[0] = address(aaveUSDC_Token);
uint256 rewards_balance = AAVEIncentivesController.getRewardsBalance(the_assets, address(this));
AAVEIncentivesController.claimRewards(the_assets, rewards_balance, address(this));
}
| 28,202 |
7 | // Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}by `operator` from `from`, this function is called. It must return its Solidity selector to confirm the token transfer.If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. / | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
| function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
| 21,654 |
9 | // If the price is acceptable relative to the trade type | while (_orderId != 0 && _bestAmount > 0 && _tradeData.loopLimit > 0 && isMatch(_orderId, _type, _orderPrice, _tradeData.price)) {
bytes32 _nextOrderId = _orders.getWorseOrderId(_orderId);
_lastTradePrice = _orderPrice;
_bestAmount = fillOrder.fillOrder(_tradeData.sender, _orderId, _bestAmount, _tradeData.tradeGroupId, _tradeData.fingerprint);
_orderId = _nextOrderId;
_orderPrice = _orders.getPrice(_orderId);
_tradeData.loopLimit -= 1;
}
| while (_orderId != 0 && _bestAmount > 0 && _tradeData.loopLimit > 0 && isMatch(_orderId, _type, _orderPrice, _tradeData.price)) {
bytes32 _nextOrderId = _orders.getWorseOrderId(_orderId);
_lastTradePrice = _orderPrice;
_bestAmount = fillOrder.fillOrder(_tradeData.sender, _orderId, _bestAmount, _tradeData.tradeGroupId, _tradeData.fingerprint);
_orderId = _nextOrderId;
_orderPrice = _orders.getPrice(_orderId);
_tradeData.loopLimit -= 1;
}
| 8,730 |
2 | // Called from invest() to confirm if the curret investment does not break our cap rule./ | function isBreakingCap(uint tokensSoldTotal) public view override returns (bool limitBroken) {
return tokensSoldTotal > maximumSellableTokens;
}
| function isBreakingCap(uint tokensSoldTotal) public view override returns (bool limitBroken) {
return tokensSoldTotal > maximumSellableTokens;
}
| 4,680 |
24 | // Clear sender's allocation | sarco_allocations[msg.sender] = 0;
| sarco_allocations[msg.sender] = 0;
| 31,164 |
5 | // admin address | address public adminAddress;
| address public adminAddress;
| 22,773 |
23 | // modifier that use to make sure account have right secure hash and valid amount for transfer | modifier accountValidateTransfer(string memory accountNumber, uint amount, uint fee)
| modifier accountValidateTransfer(string memory accountNumber, uint amount, uint fee)
| 40,512 |
287 | // allows the configurator to update the loan to value of a reserve _reserve the address of the reserve _ltv the new loan to value / | {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.baseLTVasCollateral = _ltv;
}
| {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.baseLTVasCollateral = _ltv;
}
| 9,653 |
259 | // do some accounting to add the $GOLD taxed from villagers when theyclaim their earnings amount the total $GOLD to add to the unclaimed rewards / | function _addTaxedRewards(uint256 amount) internal {
// if there's no staked vikings keep track of the gold
if (totalAlphaStaked == 0) {
unaccountedRewards += amount;
return;
}
rewardsPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked;
unaccountedRewards = 0;
}
| function _addTaxedRewards(uint256 amount) internal {
// if there's no staked vikings keep track of the gold
if (totalAlphaStaked == 0) {
unaccountedRewards += amount;
return;
}
rewardsPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked;
unaccountedRewards = 0;
}
| 17,161 |
42 | // Resume the contract | function resume() external onlyOwner {
// Move the contract out of the Paused state
isPaused = false;
}
| function resume() external onlyOwner {
// Move the contract out of the Paused state
isPaused = false;
}
| 26,218 |
34 | // emit event | emit SetWhitelistedAddress(
whitelistedAddress,
_whitelistedSTokenAddresses[holderContractAddress][
whitelistedAddress
],
holderContractAddress,
lpContractAddress,
block.timestamp
);
| emit SetWhitelistedAddress(
whitelistedAddress,
_whitelistedSTokenAddresses[holderContractAddress][
whitelistedAddress
],
holderContractAddress,
lpContractAddress,
block.timestamp
);
| 46,018 |
86 | // higher tax if bought in the same block as trading active for 72 hours (sniper protect) | if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_taxFee = _taxFee * 5;
_liquidityFee = _liquidityFee * 5;
}
| if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_taxFee = _taxFee * 5;
_liquidityFee = _liquidityFee * 5;
}
| 6,188 |
25 | // create the in-memory structure and return it | return PoolData({poolToken: poolToken, poolAddress: poolAddr, weight: weight});
| return PoolData({poolToken: poolToken, poolAddress: poolAddr, weight: weight});
| 24,468 |
7 | // In our test case we pass in the data param with bytes(1). | bool good = keccak256(abi.encodePacked(data)) ==
keccak256(abi.encodePacked(new bytes(1)));
| bool good = keccak256(abi.encodePacked(data)) ==
keccak256(abi.encodePacked(new bytes(1)));
| 29,989 |
61 | // All time sent / | function totalSentAmount(address _address) public view returns (uint256) {
return audits[_address].totalSentAmount;
}
| function totalSentAmount(address _address) public view returns (uint256) {
return audits[_address].totalSentAmount;
}
| 29,604 |
9 | // Configurables | bool public gamePaused;
address public owner;
address public ZethrBankroll;
address public ZTHTKNADDR;
ZTHInterface public ZTHTKN;
uint public contractBalance;
uint public houseEdge;
| bool public gamePaused;
address public owner;
address public ZethrBankroll;
address public ZTHTKNADDR;
ZTHInterface public ZTHTKN;
uint public contractBalance;
uint public houseEdge;
| 61,620 |
8 | // Checks that the token is owned by the sender_tokenId uint256 ID of the token/ | modifier senderMustBeTokenOwner(uint256 _tokenId) {
address tokenOwner = ownerOf(_tokenId);
require(
tokenOwner == msg.sender,
"sender must be the token owner"
);
_;
}
| modifier senderMustBeTokenOwner(uint256 _tokenId) {
address tokenOwner = ownerOf(_tokenId);
require(
tokenOwner == msg.sender,
"sender must be the token owner"
);
_;
}
| 38,579 |
64 | // Divide the signature in r, s and v variables | assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
| assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
| 6,900 |
1 | // fix the gas limit for this call | (bool result,) = address(instance).call{gas:1000000}(abi.encodeWithSignature("withdraw()")); // Must revert
| (bool result,) = address(instance).call{gas:1000000}(abi.encodeWithSignature("withdraw()")); // Must revert
| 45,766 |
1,526 | // 765 | entry "cloakedly" : ENG_ADVERB
| entry "cloakedly" : ENG_ADVERB
| 21,601 |
41 | // Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE/TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE/THEY MAY BE PERMANENTLY LOST/Throws unless `msg.sender` is the current owner, an authorized/operator, or the approved address for this NFT. Throws if `_from` is/not the current owner. Throws if `_to` is the zero address. Throws if/`_tokenId` is not a valid NFT./_from The current owner of the NFT/_to The new owner/_tokenId The NFT to transfer | function transferFrom(address _from, address _to, uint _tokenId) external payable;
| function transferFrom(address _from, address _to, uint _tokenId) external payable;
| 13,138 |
12 | // Sets up the initial state of the `ZeroEx` contract./The `ZeroEx` contract will delegatecall into this function./owner The new owner of the ZeroEx contract./ return success Magic bytes if successful. | function bootstrap(address owner) public virtual returns (bytes4 success) {
// Deploy and migrate the initial features.
// Order matters here.
// Initialize Registry.
SimpleFunctionRegistry registry = new SimpleFunctionRegistry();
LibBootstrap.delegatecallBootstrapFunction(
address(registry),
abi.encodeWithSelector(registry.bootstrap.selector, address(registry))
);
// Initialize Ownable.
Ownable ownable = new Ownable();
LibBootstrap.delegatecallBootstrapFunction(
address(ownable),
abi.encodeWithSelector(ownable.bootstrap.selector, address(ownable))
);
// Transfer ownership to the real owner.
Ownable(address(this)).transferOwnership(owner);
success = LibBootstrap.BOOTSTRAP_SUCCESS;
}
| function bootstrap(address owner) public virtual returns (bytes4 success) {
// Deploy and migrate the initial features.
// Order matters here.
// Initialize Registry.
SimpleFunctionRegistry registry = new SimpleFunctionRegistry();
LibBootstrap.delegatecallBootstrapFunction(
address(registry),
abi.encodeWithSelector(registry.bootstrap.selector, address(registry))
);
// Initialize Ownable.
Ownable ownable = new Ownable();
LibBootstrap.delegatecallBootstrapFunction(
address(ownable),
abi.encodeWithSelector(ownable.bootstrap.selector, address(ownable))
);
// Transfer ownership to the real owner.
Ownable(address(this)).transferOwnership(owner);
success = LibBootstrap.BOOTSTRAP_SUCCESS;
}
| 29,504 |
20 | // isTxLimitExempt[DEAD] = true; | _balances[_owner] = _totalSupply;
emit Transfer(address(0), _owner, _totalSupply);
| _balances[_owner] = _totalSupply;
emit Transfer(address(0), _owner, _totalSupply);
| 34,403 |
35 | // record liquidation deadline and caller | flexibleStorage().setUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, _account), _deadline);
flexibleStorage().setAddressValue(CONTRACT_NAME, _getKey(LIQUIDATION_CALLER, _account), _caller);
| flexibleStorage().setUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, _account), _deadline);
flexibleStorage().setAddressValue(CONTRACT_NAME, _getKey(LIQUIDATION_CALLER, _account), _caller);
| 23,894 |
58 | // Transfer token from owner to this contract. _owner Current owner address of token to escrow _tokenId ID of token whose approval to verify / | function _deposit(
address _owner,
uint256 _tokenId
)
internal
| function _deposit(
address _owner,
uint256 _tokenId
)
internal
| 56,560 |
151 | // Sets new block number on which presales phase one should start/This method should only be used in ongoing presale if something goes wrong/firstStageBlockStart_ The block number on which crowdsales first phase will start/ return default return True after everything is processed | function setFirstStageBlockStart(uint firstStageBlockStart_) public onlyRole(MODERATOR_ROLE) override returns (bool) {
uint oldValue = _firstStageBlockStart;
require(oldValue != firstStageBlockStart_, "Value is already set!");
_firstStageBlockStart = firstStageBlockStart_;
emit FirstStageBlockStartChanged(oldValue, firstStageBlockStart_);
return true;
}
| function setFirstStageBlockStart(uint firstStageBlockStart_) public onlyRole(MODERATOR_ROLE) override returns (bool) {
uint oldValue = _firstStageBlockStart;
require(oldValue != firstStageBlockStart_, "Value is already set!");
_firstStageBlockStart = firstStageBlockStart_;
emit FirstStageBlockStartChanged(oldValue, firstStageBlockStart_);
return true;
}
| 13,901 |
107 | // Store the function selector of `DivFailed()`. | mstore(0x00, 0x65244e4e)
| mstore(0x00, 0x65244e4e)
| 23,963 |
10 | // Whether additional borrows are allowed for this market | bool isClosing;
| bool isClosing;
| 20,469 |
36 | // Check for overflows;executes event to reflect the changes | emit LogDeposit(msg.sender, msg.value);
return true;
| emit LogDeposit(msg.sender, msg.value);
return true;
| 26,902 |
30 | // ------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner&39;s account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces------------------------------------------------------------------------ | function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens) returns (bool success) {
require(spender != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
| function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens) returns (bool success) {
require(spender != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
| 1,495 |
24 | // ------------------------------------------------------------------------ Transfer tokens from the from account to the to account The calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to_1, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to_1] = safeAdd(balances[to_1], tokens);
emit Transfer(from, to_1, tokens);
return true;
}
| function transferFrom(address from, address to_1, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to_1] = safeAdd(balances[to_1], tokens);
emit Transfer(from, to_1, tokens);
return true;
}
| 20,941 |
207 | // MINT FUNCTIONS/ | function mint(address _to, string memory uri) override external {
require(totalSupply() + 1 <= maxSupply, "NFT: out of stock");
require(_to != address(0), "NFT: invalid address");
// Using tokenId in the loop instead of totalSupply() + 1,
// because totalSupply() changed after _safeMint function call.
uint256 tokenId = totalSupply() + 1;
_safeMint(_to, tokenId);
_setTokenURI(tokenId, uri);
if (msg.sender == tx.origin) {
creators[tokenId] = msg.sender;
} else {
creators[tokenId] = address(0);
}
emit Minted(msg.sender, _to, uri, tokenId);
}
| function mint(address _to, string memory uri) override external {
require(totalSupply() + 1 <= maxSupply, "NFT: out of stock");
require(_to != address(0), "NFT: invalid address");
// Using tokenId in the loop instead of totalSupply() + 1,
// because totalSupply() changed after _safeMint function call.
uint256 tokenId = totalSupply() + 1;
_safeMint(_to, tokenId);
_setTokenURI(tokenId, uri);
if (msg.sender == tx.origin) {
creators[tokenId] = msg.sender;
} else {
creators[tokenId] = address(0);
}
emit Minted(msg.sender, _to, uri, tokenId);
}
| 31,972 |
317 | // Sets number of days claim assessment will be paused / | function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
| function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
| 33,391 |
973 | // Code executed after processing a call relayed through the GSN. / | function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal {
| function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal {
| 29,124 |
44 | // freezer can call setFreezing, transferAndFreezing | if (isFreezer(caller) && (sig == setFreezingSig || sig == transferAndFreezingSig)) {
return true;
} else {
| if (isFreezer(caller) && (sig == setFreezingSig || sig == transferAndFreezingSig)) {
return true;
} else {
| 9,383 |
25 | // Extends `BoringBatchable` with DAI `permit()`. | contract BoringBatchableWithDai is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` using DAI-derived EIP-2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
IDaiPermit token,
address holder,
address spender,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(holder, spender, nonce, expiry, true, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
| contract BoringBatchableWithDai is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` using DAI-derived EIP-2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
IDaiPermit token,
address holder,
address spender,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(holder, spender, nonce, expiry, true, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
| 39,296 |
135 | // function WETH() external pure returns (address); |
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
|
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
| 14,030 |
95 | // Transfer single sig ownership in registry | registryTransfer(seller, msg.sender, sig, 1);
| registryTransfer(seller, msg.sender, sig, 1);
| 43,571 |
13 | // ------------------------------- Signed Mint ------------------------------ / | function testLoadingSig() view public {
bytes memory sigInMemory = sig;
}
| function testLoadingSig() view public {
bytes memory sigInMemory = sig;
}
| 11,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.