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
25
// knight won
value = hitCharacter(dragonIndex, numCharacters); if (value > 0) { numCharacters--; }
value = hitCharacter(dragonIndex, numCharacters); if (value > 0) { numCharacters--; }
3,261
28
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data))
let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data))
6,516
30
// Creates a court under a specified parent court./_parent The `parent` property value of the court./_hiddenVotes The `hiddenVotes` property value of the court./_minStake The `minStake` property value of the court./_alpha The `alpha` property value of the court./_feeForJuror The `feeForJuror` property value of the court./_jurorsForCourtJump The `jurorsForCourtJump` property value of the court./_timesPerPeriod The `timesPerPeriod` property value of the court./_sortitionExtraData Extra data for sortition module./_supportedDisputeKits Indexes of dispute kits that this court will support.
function createCourt( uint96 _parent, bool _hiddenVotes, uint256 _minStake, uint256 _alpha, uint256 _feeForJuror, uint256 _jurorsForCourtJump, uint256[4] memory _timesPerPeriod, bytes memory _sortitionExtraData, uint256[] memory _supportedDisputeKits
function createCourt( uint96 _parent, bool _hiddenVotes, uint256 _minStake, uint256 _alpha, uint256 _feeForJuror, uint256 _jurorsForCourtJump, uint256[4] memory _timesPerPeriod, bytes memory _sortitionExtraData, uint256[] memory _supportedDisputeKits
20,411
46
// burn rate change, only by owneronly if necessary after community vote
function changeBurnPercentage(uint8 newRate) external onlyOwner { burnPercentage = newRate; }
function changeBurnPercentage(uint8 newRate) external onlyOwner { burnPercentage = newRate; }
33,384
79
// Retrieves fee growth data
function getFeeGrowthInside( uint256 tokenId
function getFeeGrowthInside( uint256 tokenId
27,287
31
// Add new proposal Requirements: - sender address should be whitelisted - contract should not be in paused state - proposal type should allowed proposalType - destination address should not be a valid target address - sent ether value should be consistent with value parameter details Proposal details proposalType Proposal type duration Proposal voting duration in days destination Transaction target address value Transaction value in ethers data Signed transaction data /
function addProposal( string calldata details, ProposalType proposalType, uint256 duration, address destination, uint256 value, bytes calldata data
function addProposal( string calldata details, ProposalType proposalType, uint256 duration, address destination, uint256 value, bytes calldata data
4,180
1
// if has 18 dp, exchange rate should be 1e26 if has 8 dp, exchange rate should be 1e18
if (underlyingDecimals > 8) { exchangeRate = 10**uint256(18 + underlyingDecimals - 10); } else if (underlyingDecimals < 8) {
if (underlyingDecimals > 8) { exchangeRate = 10**uint256(18 + underlyingDecimals - 10); } else if (underlyingDecimals < 8) {
11,758
112
// Update the given pool's JFI distribution point. Can only be called by the owner.
function set(uint256 _pid, uint256 _distPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalDistPoint = totalDistPoint.sub(poolInfo[_pid].distPoint).add(_distPoint); poolInfo[_pid].distPoint = _distPoint; updatePoolsJfiLeftInternal(); }
function set(uint256 _pid, uint256 _distPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalDistPoint = totalDistPoint.sub(poolInfo[_pid].distPoint).add(_distPoint); poolInfo[_pid].distPoint = _distPoint; updatePoolsJfiLeftInternal(); }
15,042
117
// Checks whether a token is boosted to receivebigger staking rewards_tokenId ID of token to checkreturn whether the token is boosted /
function isBoostedToken(uint256 _tokenId) public view returns (bool) { return boostedNftIds.contains(_tokenId); }
function isBoostedToken(uint256 _tokenId) public view returns (bool) { return boostedNftIds.contains(_tokenId); }
39,426
4,246
// 2125
entry "biochronologically" : ENG_ADVERB
entry "biochronologically" : ENG_ADVERB
22,961
126
// Returns the token identifier for the `_index`th NFT. Sort order is not specified. _index A counter less than `totalSupply()`.return Token id. /
function tokenByIndex( uint256 _index ) external view
function tokenByIndex( uint256 _index ) external view
18,895
52
// we should not reach to this point
assert(false);
assert(false);
32,166
14
// Get the timestamp for checkpoint `_idx` for `_addr`/_addr User wallet address/_idx User epoch number/ return Epoch time of the checkpoint
function user_point_history__ts(address _addr, uint _idx) external view returns (uint) { return user_point_history[_addr][_idx].ts; }
function user_point_history__ts(address _addr, uint _idx) external view returns (uint) { return user_point_history[_addr][_idx].ts; }
18,654
4
// /
function hashLeftRight(bytes32 _left, bytes32 _right) public pure returns (bytes32)
function hashLeftRight(bytes32 _left, bytes32 _right) public pure returns (bytes32)
29,384
92
// enforce that the user is a member
require(shares >= minimumShare, "You must be a member!");
require(shares >= minimumShare, "You must be a member!");
17,761
62
// AdminUpgradeabilityProxy This contract combines an upgradeability proxy with an authorizationmechanism for administrative tasks.All external functions in this contract must be guarded by the`ifAdmin` modifier. See ethereum/solidity3864 for a Solidityfeature proposal that would enable this to be done automatically. /
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
10,291
72
// require(getBalance().add(msg.value) <= getMaximumDepositPoolSize(), "The deposit pool size after depositing exceeds the maximum size"); Load contracts
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
35,140
32
// depositor contract used to deposit underlyings
address public depositor;
address public depositor;
52,442
40
// resetuserInsuranceFee[user][i].insuranceReturn = 0;userInsuranceFee[user][i].insuraceFee = 0;userInsuranceFee[user][i].flightInsured = bytes32(0);
return reFund;
return reFund;
27,026
143
// solhint-disable func-name-mixedcase
interface IDerivedToken { /** * @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); }
interface IDerivedToken { /** * @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); }
51,759
36
// set new icoPercent/newIcoPercent new value of icoPercent
function setIcoPercent(uint256 newIcoPercent) public
function setIcoPercent(uint256 newIcoPercent) public
35,031
89
// Deposit the yield-tokens to the recipient.
return _deposit(yieldToken, amountYieldTokens, recipient);
return _deposit(yieldToken, amountYieldTokens, recipient);
15,162
20
// Transfer tokens from other address Send `_value` tokens to `_to` on behalf of `_from`_from The address of the sender _to The address of the recipient _value the amount to send /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
1,226
13
// adds to claim list with specified amounts
function addToWhitelist(address[] memory _listToAdd) public onlyOwner { uint256 totalAddresses = _listToAdd.length; for (uint256 i = 0; i < totalAddresses; i++) { whitelist[_listToAdd[i]] = whitelistMints; }
function addToWhitelist(address[] memory _listToAdd) public onlyOwner { uint256 totalAddresses = _listToAdd.length; for (uint256 i = 0; i < totalAddresses; i++) { whitelist[_listToAdd[i]] = whitelistMints; }
40,597
10
// reveal TZRKT -> DGVEH /
function revealToDGVEH(uint256 tzrktTokenId) public returns (uint256) { require(_tzrktContract != address(0), "revealToDGVEH: _tzrktContract is the zero address."); require(_dgvehContract != address(0), "revealToDGVEH: _dgvehContract is the zero address."); ITZRKT(_tzrktContract).burn(tzrktTokenId); uint256 dgvehTokenId = IDGVEH(_dgvehContract).mint(_msgSender()); emit DGVEHRevealed(_msgSender(), dgvehTokenId); return dgvehTokenId; }
function revealToDGVEH(uint256 tzrktTokenId) public returns (uint256) { require(_tzrktContract != address(0), "revealToDGVEH: _tzrktContract is the zero address."); require(_dgvehContract != address(0), "revealToDGVEH: _dgvehContract is the zero address."); ITZRKT(_tzrktContract).burn(tzrktTokenId); uint256 dgvehTokenId = IDGVEH(_dgvehContract).mint(_msgSender()); emit DGVEHRevealed(_msgSender(), dgvehTokenId); return dgvehTokenId; }
23,302
23
// function to add a new organization to the network. creates org_orgId unique organization id_enodeId enode id linked to the organization_ip IP of node_port tcp port of node_raftport raft port of node_account account id. this will have the org admin privileges/
function addOrg(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _account, address _caller) public onlyInterface
function addOrg(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _account, address _caller) public onlyInterface
20,708
7
// Returns the memory address of the first byte of the first occurrence of `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; }
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; }
11,968
46
// Update the market with the new manager address,
runningDepositTotal = runningDepositTotal.add(market.deposited());
runningDepositTotal = runningDepositTotal.add(market.deposited());
16,276
19
// Check if the NFT is listed for sale
require(seller != address(0), "NFT is not listed for sale.");
require(seller != address(0), "NFT is not listed for sale.");
9,308
91
// Emitted when the pause is lifted. /
event Unpaused();
event Unpaused();
841
0
// The ZORA Module Registrar
address public immutable registrar;
address public immutable registrar;
26,985
115
// If parent is 0x0 = dont existIf parent is not 0x0 = exist
return !(parent[_address]==address(0x0));
return !(parent[_address]==address(0x0));
14,961
1
// Pre block is not used in "while mode"
} lt(i, length) {
} lt(i, length) {
21,604
25
// Dynamic max expansion percent
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for masonry maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn PEG and mint Bond) maxDebtRatioPercent = 3500; // Upto 35% supply of Bond to purchase
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for masonry maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn PEG and mint Bond) maxDebtRatioPercent = 3500; // Upto 35% supply of Bond to purchase
21,121
57
// 未开始
NotStarted,
NotStarted,
4,375
1,436
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
lockedCollateral = startCollateral.mul(ratio);
2,041
25
// transfer the token from address of this contract to address of the user (executing the withdrawToken() function)
tokenContract.transfer(to, _amount);
tokenContract.transfer(to, _amount);
6,396
67
// Delete the old entry for the moved value
set.values.pop(); return true;
set.values.pop(); return true;
7,070
3
// Will revert if subscription is not set and funded.
requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, _numWords ); s_requests[requestId] = RequestStatus({ randomNumber: new uint256[](0), exists: true,
requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, _numWords ); s_requests[requestId] = RequestStatus({ randomNumber: new uint256[](0), exists: true,
26,745
30
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } }
import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } }
3,702
101
// Harvest
function harvest() public { require(msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist, "No harvest from contract"); dRewards(pool).getReward(); //DF -> want uint256 _df = IERC20(df).balanceOf(address(this)); if(_df <= DFThreshold) return; if (_df > 0) { _swap(df, want, _df); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Performance fee IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } }
function harvest() public { require(msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist, "No harvest from contract"); dRewards(pool).getReward(); //DF -> want uint256 _df = IERC20(df).balanceOf(address(this)); if(_df <= DFThreshold) return; if (_df > 0) { _swap(df, want, _df); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Performance fee IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } }
74,536
41
// return oracle name
function getProviderTitle(address provider) public view returns (bytes32) { return getTitle(provider); }
function getProviderTitle(address provider) public view returns (bytes32) { return getTitle(provider); }
69,734
57
// emit XTransfer event
emit XTransfer(msg.sender, toBlockchain, to, amount, id);
emit XTransfer(msg.sender, toBlockchain, to, amount, id);
46,219
48
// called by the admin to unpause, returns to normal stateReset genesis state. Once paused, the rounds would need to be kickstarted by genesis /
function unpause() external whenPaused onlyAdmin { genesisStarted = false; genesisLocked = false; _unpause(); emit Unpause(currentRound); }
function unpause() external whenPaused onlyAdmin { genesisStarted = false; genesisLocked = false; _unpause(); emit Unpause(currentRound); }
46,065
94
// transfer tokens to src --> dst. src address should be valid ethereum address. dst address should be valid ethereum address. amount should be greater than zero. src the source address. dst the destination address. amount number of token to transfer. /
function _transferTokens( address src, address dst, uint256 amount
function _transferTokens( address src, address dst, uint256 amount
30,715
1
// This checks for a bug that caused a crash because of continued analysis.
contract C { mapping (uint => uint) m; function f() public { m(1) = 2; } }
contract C { mapping (uint => uint) m; function f() public { m(1) = 2; } }
39,691
351
// TODO: check max size of array before remaking this becomes untenable/Deletes an existing entry/Owner can delete an existing entry/ofAsset address for which specific information is requested
function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists)
function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists)
25,083
176
// The Pool cannot be finalized, but if it is, account cannot be the Pool Delegate.
require(!_pool.isPoolFinalized() || from != _pool.poolDelegate(), "SL:STAKE_LOCKED"); _;
require(!_pool.isPoolFinalized() || from != _pool.poolDelegate(), "SL:STAKE_LOCKED"); _;
10,568
4
// If your deposit greater than balance.You will get the balance amount.
if (amount > address(this).balance) { amount = address(this).balance; }
if (amount > address(this).balance) { amount = address(this).balance; }
24,735
138
// Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. spender The address which will spend the funds. value The amount of tokens to be spent.return A boolean that indicates if the operation was successful. /
function approve(address spender, uint256 value) external override returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
function approve(address spender, uint256 value) external override returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
28,279
17
// View functions /
function getTarget( string memory _funcId) // example: "takeLoanOrderAsTrader(address[8],uint256[11],bytes,address,uint256,bytes)" public view returns (address)
function getTarget( string memory _funcId) // example: "takeLoanOrderAsTrader(address[8],uint256[11],bytes,address,uint256,bytes)" public view returns (address)
33,022
83
// Add the contents of b to the array
for { let i := 0 } lt(i, loopsb) {
for { let i := 0 } lt(i, loopsb) {
71,911
30
// Command start at 1 but array start at 0
if (command.status != Status.Pending) revert CommandNotPending(); commands[commandNb - 1].status = Status.Accepted;
if (command.status != Status.Pending) revert CommandNotPending(); commands[commandNb - 1].status = Status.Accepted;
28,667
14
// Setup simple enumeration
indexToTokenId[totalTokens] = _tokenId; totalTokens = totalTokens + 1;
indexToTokenId[totalTokens] = _tokenId; totalTokens = totalTokens + 1;
15,477
770
// Max BABL Cap to claim by sig
uint256 internal constant MAX_BABL_CAP_REACHED = 123;
uint256 internal constant MAX_BABL_CAP_REACHED = 123;
76,627
111
// Emitted when set new delegate percent
event NewDelegatePercent(uint256 oldDelegatePercent, uint256 newDelegatePercent);
event NewDelegatePercent(uint256 oldDelegatePercent, uint256 newDelegatePercent);
13,260
0
// Copy the free memory pointer so that we can restore it later.
let m := mload(0x40)
let m := mload(0x40)
36,740
171
// Function to liquidate a position if its Health Factor drops below 1- The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receivesa proportionally amount of the `collateralAsset` plus a bonus to cover market risk collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation debtAsset The address of the underlying borrowed asset to be repaid with the liquidation user The address of the borrower getting liquidated debtToCover The debt amount of borrowed `asset` the liquidator wants to cover receiveAToken `true` if the liquidators wants to receive the collateral
) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); }
) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); }
60,626
0
// Interface of Asset /
interface IAsset is IERC20Metadata { function aggregateAccount() external view returns (address); function cash() external view returns (uint256); function liability() external view returns (uint256); function underlyingToken() external view returns (address); function underlyingTokenBalance() external view returns (uint256); function transferUnderlyingToken(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function burn(address to, uint256 amount) external; function addCash(uint256 amount) external; function removeCash(uint256 amount) external; function addLiability(uint256 amount) external; function removeLiability(uint256 amount) external; function getCompensationRatio() external view returns (uint256); }
interface IAsset is IERC20Metadata { function aggregateAccount() external view returns (address); function cash() external view returns (uint256); function liability() external view returns (uint256); function underlyingToken() external view returns (address); function underlyingTokenBalance() external view returns (uint256); function transferUnderlyingToken(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function burn(address to, uint256 amount) external; function addCash(uint256 amount) external; function removeCash(uint256 amount) external; function addLiability(uint256 amount) external; function removeLiability(uint256 amount) external; function getCompensationRatio() external view returns (uint256); }
33,804
78
// need to send penalty amount to the pool
require(_stakingPool.transfer(penaltyAddress, penaltyAmount), 'TokenSpring: transfer into staking pool failed');
require(_stakingPool.transfer(penaltyAddress, penaltyAmount), 'TokenSpring: transfer into staking pool failed');
40,084
13
// 装备嵌入宝石
function armsAddGemstone( address addr, uint256 armsTokenId, uint256 gemstoneTokenId, uint256 position
function armsAddGemstone( address addr, uint256 armsTokenId, uint256 gemstoneTokenId, uint256 position
9,235
11
// _MINT FUNCTION
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
16,033
99
// Function for retrieving the total deposits amount./
function totalDeposits() external view returns (uint256);
function totalDeposits() external view returns (uint256);
52,044
16
// Emitted when an End Auction Event is completed/uuid The generated Unique uuid/tokenId The NFT tokenId/tokenContract The NFT Contract address/quantity The total quantity of the ERC1155 token if ERC721 it is 1/tokenOwner The address of the Token Owner/highestBidder Address of the highest bidder/amount Fixed Price/paymentToken ERC20 address chosen by TokenOwner for Payments/marketplaceAddress Address of the Platform/platformFee Fee sent to the Platform Address/bidderlist Bid History List
event AuctionClosed( string uuid, uint256 indexed tokenId, address indexed tokenContract, uint256 quantity, address indexed tokenOwner, address highestBidder, uint256 amount, uint256 tax, address paymentToken,
event AuctionClosed( string uuid, uint256 indexed tokenId, address indexed tokenContract, uint256 quantity, address indexed tokenOwner, address highestBidder, uint256 amount, uint256 tax, address paymentToken,
26,940
45
// otherwise claim the tokens
_sourceToken.safeTransferFrom(msg.sender, address(this), _amount);
_sourceToken.safeTransferFrom(msg.sender, address(this), _amount);
40,756
52
// variable to keep track of what addresses are allowed to call transfer functions when token is paused. /
mapping (address => bool) public allowedTransfers;
mapping (address => bool) public allowedTransfers;
41,765
4
// first move must be a concluded Commitment (transition rules will ensure this for the other commitments)
require( _fromCommitment.isConclude(), "fromCommitment must be Conclude" );
require( _fromCommitment.isConclude(), "fromCommitment must be Conclude" );
8,772
61
// The index of the challenge is equal to the index of a newly created dispute in disputeIDs array.
challenge.challengeID = request.disputeIDs.length - 1; challenge.challenger = msg.sender; challenge.challengedSubmission = _submissionID; challenge.duplicateSubmissionIndex = submissionToIndex[_duplicateID]; request.rounds[request.disputeIDs.length - 1].length++; request.rounds[request.rounds.length++].length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute(
challenge.challengeID = request.disputeIDs.length - 1; challenge.challenger = msg.sender; challenge.challengedSubmission = _submissionID; challenge.duplicateSubmissionIndex = submissionToIndex[_duplicateID]; request.rounds[request.disputeIDs.length - 1].length++; request.rounds[request.rounds.length++].length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute(
39,100
14
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply;
if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply;
19,985
3
// Record a new seal in the registry. /
function recordSeal(bytes32 id, bytes32 sealValue) public onlyWhitelisted { require(seals[id].value == bytes32(0x0)); seals[id] = Seal({value: sealValue}); emit LogNewSealRecorded(id, sealValue); }
function recordSeal(bytes32 id, bytes32 sealValue) public onlyWhitelisted { require(seals[id].value == bytes32(0x0)); seals[id] = Seal({value: sealValue}); emit LogNewSealRecorded(id, sealValue); }
41,444
1
// Calculates the WETH value of an LP token /
function lpTokenValue(uint256 amount, IUniswapV2Pair lpToken) public virtual override view returns(uint256) { (uint256 token0Reserve, uint256 token1Reserve,) = lpToken.getReserves(); address token0 = lpToken.token0(); address token1 = lpToken.token1(); if (token0 == address(weth)) { return amount.mul(token0Reserve).mul(2).div(lpToken.totalSupply()); } if (token1 == address(weth)) { return amount.mul(token1Reserve).mul(2).div(lpToken.totalSupply()); } if (IUniswapV2Factory(lpToken.factory()).getPair(token0, address(weth)) != address(0)) { (uint256 wethReserve0, uint256 token0ToWethReserve0) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token0); uint256 tmp0 = amount.mul(token0Reserve).mul(wethReserve0).mul(2); return tmp0.div(token0ToWethReserve0).div(lpToken.totalSupply()); } require( IUniswapV2Factory(lpToken.factory()).getPair(token1, address(weth)) != address(0), "Neither token0-weth nor token1-weth pair exists"); (uint256 wethReserve1, uint256 token1ToWethReserve1) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token1); uint256 tmp1 = amount.mul(token1Reserve).mul(wethReserve1).mul(2); return tmp1.div(token1ToWethReserve1).div(lpToken.totalSupply()); }
function lpTokenValue(uint256 amount, IUniswapV2Pair lpToken) public virtual override view returns(uint256) { (uint256 token0Reserve, uint256 token1Reserve,) = lpToken.getReserves(); address token0 = lpToken.token0(); address token1 = lpToken.token1(); if (token0 == address(weth)) { return amount.mul(token0Reserve).mul(2).div(lpToken.totalSupply()); } if (token1 == address(weth)) { return amount.mul(token1Reserve).mul(2).div(lpToken.totalSupply()); } if (IUniswapV2Factory(lpToken.factory()).getPair(token0, address(weth)) != address(0)) { (uint256 wethReserve0, uint256 token0ToWethReserve0) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token0); uint256 tmp0 = amount.mul(token0Reserve).mul(wethReserve0).mul(2); return tmp0.div(token0ToWethReserve0).div(lpToken.totalSupply()); } require( IUniswapV2Factory(lpToken.factory()).getPair(token1, address(weth)) != address(0), "Neither token0-weth nor token1-weth pair exists"); (uint256 wethReserve1, uint256 token1ToWethReserve1) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token1); uint256 tmp1 = amount.mul(token1Reserve).mul(wethReserve1).mul(2); return tmp1.div(token1ToWethReserve1).div(lpToken.totalSupply()); }
17,558
141
// // TimeUtils Library that accompanies Decimal to convert unix time into Decimal.D256 values /
library TimeUtils { /** * @notice Number of seconds in a single day */ uint256 private constant SECONDS_IN_DAY = 86400; /** * @notice Converts an integer number of seconds to a Decimal.D256 amount of days * @param s Number of seconds to convert * @return Equivalent amount of days as a Decimal.D256 */ function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) { return Decimal.ratio(s, SECONDS_IN_DAY); } }
library TimeUtils { /** * @notice Number of seconds in a single day */ uint256 private constant SECONDS_IN_DAY = 86400; /** * @notice Converts an integer number of seconds to a Decimal.D256 amount of days * @param s Number of seconds to convert * @return Equivalent amount of days as a Decimal.D256 */ function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) { return Decimal.ratio(s, SECONDS_IN_DAY); } }
63,097
36
// user reward payouts per data contracts
mapping(address => mapping(address => uint256)) private _rewardPayouts;
mapping(address => mapping(address => uint256)) private _rewardPayouts;
41,084
29
// Set metadata for music game data format: description, imageURI, animationURI, tokenId
( string memory description, string memory imageURI, string memory animationURI ) = abi.decode(initialData, (string, string, string)); bytes memory data = abi.encode( description, imageURI, animationURI, _lastMintedTokenId()
( string memory description, string memory imageURI, string memory animationURI ) = abi.decode(initialData, (string, string, string)); bytes memory data = abi.encode( description, imageURI, animationURI, _lastMintedTokenId()
11,352
162
// Distribute the `tRewardFee` tokens to all holders that are included in receiving reward.amount received is based on how many token one owns. /
function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; }
function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; }
33,516
192
// bytes4(keccak256('balanceOf(address)')) == 0x70a08231bytes4(keccak256('ownerOf(uint256)')) == 0x6352211ebytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3bytes4(keccak256('getApproved(uint256)')) == 0x081812fcbytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872ddbytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0ebytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd /
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
1,995
165
// The total cost is the price plus flat rate dividends based on claim dividends.
uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); return price.add(flatDividends);
uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); return price.add(flatDividends);
13,317
96
// ark, round 48
st0 := addmod(st0, 0x04e1181763050e58013444dbcb99f1902b11bc25d90bbdca408d3819f4fed32b, q) st1 := addmod(st1, 0x0fdb253dee83869d40c335ea64de8c5bb10eb82db08b5e8b1f5e5552bfd05f23, q) st2 := addmod(st2, 0x058cbe8a9a5027bdaa4efb623adead6275f08686f1c08984a9d7c5bae9b4f1c0, q)
st0 := addmod(st0, 0x04e1181763050e58013444dbcb99f1902b11bc25d90bbdca408d3819f4fed32b, q) st1 := addmod(st1, 0x0fdb253dee83869d40c335ea64de8c5bb10eb82db08b5e8b1f5e5552bfd05f23, q) st2 := addmod(st2, 0x058cbe8a9a5027bdaa4efb623adead6275f08686f1c08984a9d7c5bae9b4f1c0, q)
8,308
205
// Converts a bytes32 UUID to a UUID string with dashes e9071858e63b4f2792d70603235c0b8c => e9071858-e63b-4f27-92d7-0603235c0b8c
function bytes32ToUUIDString(bytes32 b) internal pure returns (string memory) { bytes memory bytesArray = new bytes(36); uint j; for (uint256 i; i < 32; i++) { bytesArray[j] = b[i];
function bytes32ToUUIDString(bytes32 b) internal pure returns (string memory) { bytes memory bytesArray = new bytes(36); uint j; for (uint256 i; i < 32; i++) { bytesArray[j] = b[i];
39,094
419
// "destroy" the temporary swap fee (like _initialTokens above) in case a subclass tries to use it
_initialSwapFee = 0;
_initialSwapFee = 0;
6,484
65
// ============================================================================== _ _|_ __ __ | _ _ || _.(/_>< | (/_| | |(_||(_(_|||_\.==============================================================================
function getPlayerID(address _addr) isRegisteredGame() external returns (uint256)
function getPlayerID(address _addr) isRegisteredGame() external returns (uint256)
25,073
61
// The threshold (denominated in the reward token) over which thevault will auto harvest on allocate calls. /
function rewardLiquidationThreshold() external pure returns (uint256);
function rewardLiquidationThreshold() external pure returns (uint256);
37,449
14
// _addStakeholder takes care of adding a stakeholder to the stakeholders array /
function _addStakeholder(address staker) internal returns (uint256){ // Push a empty item to the Array to make space for our new stakeholder stakeholders.push(); // Calculate the index of the last item in the array by Len-1 uint256 userIndex = stakeholders.length - 1; // Assign the address to the new index stakeholders[userIndex].user = staker; // Add index to the stakeHolders stakes[staker] = userIndex; return userIndex; }
function _addStakeholder(address staker) internal returns (uint256){ // Push a empty item to the Array to make space for our new stakeholder stakeholders.push(); // Calculate the index of the last item in the array by Len-1 uint256 userIndex = stakeholders.length - 1; // Assign the address to the new index stakeholders[userIndex].user = staker; // Add index to the stakeHolders stakes[staker] = userIndex; return userIndex; }
30,036
15
// Stake ERC20 Tokens.
* @dev See {_stake}. Override that to implement custom logic. * * @param _amount Amount to stake. */ function stake(uint256 _amount) external payable nonReentrant { _stake(_amount); }
* @dev See {_stake}. Override that to implement custom logic. * * @param _amount Amount to stake. */ function stake(uint256 _amount) external payable nonReentrant { _stake(_amount); }
9,470
10
// here for debugging/mock purposes. safeTransferFrom(...) is error prone with ethers.js
function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); safeTransferFrom(from, to, tokenId, ""); }
function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); safeTransferFrom(from, to, tokenId, ""); }
40,451
42
// Check that the receiver hasn't been already added
FundingReceiver storage newReceiver = fundingReceivers[receiver][targetFunctionSignature]; require(newReceiver.lastUpdateTime == 0, "MinMaxRewardsAdjuster/receiver-already-added");
FundingReceiver storage newReceiver = fundingReceivers[receiver][targetFunctionSignature]; require(newReceiver.lastUpdateTime == 0, "MinMaxRewardsAdjuster/receiver-already-added");
3,221
18
// Add a new listing to the listingCachesboardCache The OptionBoardCache object the listing is being added to listingId The id of the OptionListing. /
function _addNewListingToListingCache(OptionBoardCache storage boardCache, uint listingId) internal { IOptionMarket.OptionListing memory listing = getOptionMarketListing(listingId); // This is only called when a new board or a new listing is added, so exposure values will be 0 OptionListingCache storage listingCache = listingCaches[listing.id]; listingCache.id = listing.id; listingCache.strike = listing.strike; listingCache.boardId = listing.boardId; listingCache.skew = listing.skew; boardCache.listings.push(listingId); }
function _addNewListingToListingCache(OptionBoardCache storage boardCache, uint listingId) internal { IOptionMarket.OptionListing memory listing = getOptionMarketListing(listingId); // This is only called when a new board or a new listing is added, so exposure values will be 0 OptionListingCache storage listingCache = listingCaches[listing.id]; listingCache.id = listing.id; listingCache.strike = listing.strike; listingCache.boardId = listing.boardId; listingCache.skew = listing.skew; boardCache.listings.push(listingId); }
18,511
0
// VARIABLE INITIALIZATION /
uint256 constant public startTime = 1507032000; // 10/03/2017 @ 12:00pm (UTC) crowdsale start time (in seconds) uint256 constant public endTime = 1509494340; // 10/31/2017 @ 11:59pm (UTC) crowdsale end time (in seconds) uint256 constant internal week2Start = startTime + (7 days); // 10/10/2017 @ 12:00pm (UTC) week 2 price begins uint256 constant internal week3Start = week2Start + (7 days); // 10/17/2017 @ 12:00pm (UTC) week 3 price begins uint256 constant internal week4Start = week3Start + (7 days); // 10/25/2017 @ 12:00pm (UTC) week 4 price begins uint256 public totalPresaleTokensYetToAllocate; // Counter that keeps track of presale tokens yet to allocate address public beneficiary = 0x0; // address to receive all ether contributions address public tokenAddress = 0x0; // address of the token itself
uint256 constant public startTime = 1507032000; // 10/03/2017 @ 12:00pm (UTC) crowdsale start time (in seconds) uint256 constant public endTime = 1509494340; // 10/31/2017 @ 11:59pm (UTC) crowdsale end time (in seconds) uint256 constant internal week2Start = startTime + (7 days); // 10/10/2017 @ 12:00pm (UTC) week 2 price begins uint256 constant internal week3Start = week2Start + (7 days); // 10/17/2017 @ 12:00pm (UTC) week 3 price begins uint256 constant internal week4Start = week3Start + (7 days); // 10/25/2017 @ 12:00pm (UTC) week 4 price begins uint256 public totalPresaleTokensYetToAllocate; // Counter that keeps track of presale tokens yet to allocate address public beneficiary = 0x0; // address to receive all ether contributions address public tokenAddress = 0x0; // address of the token itself
19,198
21
// 10% chance to steal NTF
if (getSomeRandomNumber(vikingMinted, 100) >= 10) { return msg.sender; // 90% }
if (getSomeRandomNumber(vikingMinted, 100) >= 10) { return msg.sender; // 90% }
22,375
2
// Returns the amount of locks on the token. /
function lockCount(uint256 _tokenId) external view returns (uint256);
function lockCount(uint256 _tokenId) external view returns (uint256);
26,420
57
// pnL of the position
profit += _closePositionOnMarket(user.positionSize, tentativeVQuoteAmount) + user.openNotional;
profit += _closePositionOnMarket(user.positionSize, tentativeVQuoteAmount) + user.openNotional;
3,137
18
// Update the baseLPToken amount that will be deposited
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
9,793
15
// Mintable ERC20
IERC20(token.tokenAddress).mint(_to, _amount);
IERC20(token.tokenAddress).mint(_to, _amount);
23,074
53
// Transfer all the funds (less the bounty) to the ZBR crowdsale contract to buy tokens.Throws if the crowdsale hasn't started yet or has already completed, preventing loss of funds.
token.proxyPayment.value(this.balance - bounty)(address(this));
token.proxyPayment.value(this.balance - bounty)(address(this));
13,141
24
// The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
IValidatorSetAuRa public validatorSetContract;
49,004
15
// Accumulates the sum of the weights
uint256 denominator;
uint256 denominator;
7,282
78
// incase of half-way error
function inCaseTokenGetsStuck(IERC20 _TokenAddress) onlyOwner public { uint qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(msg.sender, qty); }
function inCaseTokenGetsStuck(IERC20 _TokenAddress) onlyOwner public { uint qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(msg.sender, qty); }
46,548
57
// stakingToken The token users deposit as stake. distributionToken The token users receive as they unstake. maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit. startBonus_ Starting time bonus, BONUS_DECIMALS fixed point. e.g. 25% means user gets 25% of max distribution tokens. bonusPeriodSec_ Length of time for bonus to increase linearly to max. initialSharesPerToken Number of shares to mint per staking token on first stake. /
constructor( IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken, address referrerBook_
constructor( IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken, address referrerBook_
3,850
93
// AllowanceCrowdsale Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. /
contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } }
contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } }
7,112
5
// See interface for documentation.
contract AWETH is IAWETH { address payable public override immutable weth; constructor(address payable weth_) public { weth = weth_; } // See interface for documentation. function depositAndTransferFromThenCall(uint amount, address to, bytes calldata data) external override payable { if (msg.value > 0) { IWETH9(weth).deposit{value: msg.value}(); } if (amount > 0) { IWETH9(weth).transferFrom(msg.sender, address(this), amount); } uint total = msg.value + amount; require(total >= msg.value, 'OVERFLOW'); // nobody should be this rich. require(total > 0, 'ZERO_INPUTS'); IWETH9(weth).approve(to, total); (bool success,) = to.call(data); require(success, 'TO_CALL_FAILED'); // unwrap and refund any unspent WETH. withdrawTo(msg.sender); } // Only the WETH contract may send ETH via a call to withdraw. receive() payable external { require(msg.sender == weth, 'WETH_ONLY'); } // See interface for documentation. function withdrawTo(address payable to) public override { uint wethBalance = IWETH9(weth).balanceOf(address(this)); if (wethBalance > 0) { IWETH9(weth).withdraw(wethBalance); (bool success,) = to.call{value: wethBalance}(''); require(success, 'WITHDRAW_TO_CALL_FAILED'); } } }
contract AWETH is IAWETH { address payable public override immutable weth; constructor(address payable weth_) public { weth = weth_; } // See interface for documentation. function depositAndTransferFromThenCall(uint amount, address to, bytes calldata data) external override payable { if (msg.value > 0) { IWETH9(weth).deposit{value: msg.value}(); } if (amount > 0) { IWETH9(weth).transferFrom(msg.sender, address(this), amount); } uint total = msg.value + amount; require(total >= msg.value, 'OVERFLOW'); // nobody should be this rich. require(total > 0, 'ZERO_INPUTS'); IWETH9(weth).approve(to, total); (bool success,) = to.call(data); require(success, 'TO_CALL_FAILED'); // unwrap and refund any unspent WETH. withdrawTo(msg.sender); } // Only the WETH contract may send ETH via a call to withdraw. receive() payable external { require(msg.sender == weth, 'WETH_ONLY'); } // See interface for documentation. function withdrawTo(address payable to) public override { uint wethBalance = IWETH9(weth).balanceOf(address(this)); if (wethBalance > 0) { IWETH9(weth).withdraw(wethBalance); (bool success,) = to.call{value: wethBalance}(''); require(success, 'WITHDRAW_TO_CALL_FAILED'); } } }
19,817