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 |
|---|---|---|---|---|
34 | // Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth/newSellPrice Price the users can sell to the contract/newBuyPrice Price users can buy from the contract | function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
| function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
| 14,362 |
5 | // Transfers `value` amount of tokens to address `to`. Reverts if `to` is the zero address. Reverts if the sender does not have enough balance. Emits an {IERC20-Transfer} event. Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event. to The receiver account. value The amount of tokens to transfer.return True if the transfer succeeds, false otherwise. / | function transfer(address to, uint256 value) external returns (bool);
| function transfer(address to, uint256 value) external returns (bool);
| 29,916 |
11 | // user is not last user | if (index < users.length.sub(1)) {
address lastUser = users[users.length.sub(1)];
users[index] = lastUser;
userIndex[lastUser] = index;
}
| if (index < users.length.sub(1)) {
address lastUser = users[users.length.sub(1)];
users[index] = lastUser;
userIndex[lastUser] = index;
}
| 19,704 |
0 | // This interface contains the commonn data provided by all the EthItem models / | interface IEthItemModelBase is IEthItemMainInterface {
/**
* @dev Contract Initialization, the caller of this method should be a Contract containing the logic to provide the EthItemERC20WrapperModel to be used to create ERC20-based objectIds
* @param name the chosen name for this NFT
* @param symbol the chosen symbol (Ticker) for this NFT
*/
function init(string calldata name, string calldata symbol) external;
/**
* @return modelVersionNumber The version number of the Model, it should be progressive
*/
function modelVersion() external pure returns(uint256 modelVersionNumber);
/**
* @return factoryAddress the address of the Contract which initialized this EthItem
*/
function factory() external view returns(address factoryAddress);
} | interface IEthItemModelBase is IEthItemMainInterface {
/**
* @dev Contract Initialization, the caller of this method should be a Contract containing the logic to provide the EthItemERC20WrapperModel to be used to create ERC20-based objectIds
* @param name the chosen name for this NFT
* @param symbol the chosen symbol (Ticker) for this NFT
*/
function init(string calldata name, string calldata symbol) external;
/**
* @return modelVersionNumber The version number of the Model, it should be progressive
*/
function modelVersion() external pure returns(uint256 modelVersionNumber);
/**
* @return factoryAddress the address of the Contract which initialized this EthItem
*/
function factory() external view returns(address factoryAddress);
} | 11,191 |
179 | // change reveal state | function flipRevealed() external onlyOwner {
revealed = !revealed;
}
| function flipRevealed() external onlyOwner {
revealed = !revealed;
}
| 81,318 |
5 | // Validator/voter => value | uint highestVote;
mapping (address => uint8) votes;
address[] validators;
| uint highestVote;
mapping (address => uint8) votes;
address[] validators;
| 7,529 |
175 | // if there is some eth left (0x fee), return it to user | if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
| if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
| 6,171 |
13 | // Production networks are placed higher to minimise the number of checks performed and therefore reduce gas. By the same rationale, mainnet comes before Polygon as it's more expensive. | case 1 {
| case 1 {
| 57,035 |
150 | // If the returned progress data is empty, then the proposal completed and it should not be executed again. | return nextProgressData.length == 0;
| return nextProgressData.length == 0;
| 12,898 |
2 | // Pauses all functions guarded by Pause | * See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
| * See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
| 40,578 |
162 | // The sum of all the unclaimed reward tokens. |
uint256 constant pointMultiplier = 10e22;
|
uint256 constant pointMultiplier = 10e22;
| 46,250 |
79 | // can not buy from yourself | if (obj.monsterId == 0 || obj.trainer == msg.sender) {
revert();
}
| if (obj.monsterId == 0 || obj.trainer == msg.sender) {
revert();
}
| 54,206 |
8 | // Staker info | struct Staker {
// Amount of tokens staked by the taker
uint256 amountStaked;
// Staked tokens
StakedToken[] stakedTokens;
// Last time of the rewards were calculated for this user
uint256 timeOfLastUpdate;
// Calculate, but unclaimed rewards for the User. The rewards are
// calculated each time the user wrties to the Smart Contract
uint256 unclaimedRewards;
}
| struct Staker {
// Amount of tokens staked by the taker
uint256 amountStaked;
// Staked tokens
StakedToken[] stakedTokens;
// Last time of the rewards were calculated for this user
uint256 timeOfLastUpdate;
// Calculate, but unclaimed rewards for the User. The rewards are
// calculated each time the user wrties to the Smart Contract
uint256 unclaimedRewards;
}
| 16,244 |
4 | // Called through DSProxy calls strategy storage contract | contract StrategyProxy is StrategyModel, AdminAuth, ProxyPermission, CoreHelper {
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
/// @notice Calls strategy sub through DSProxy
/// @param _name Name of the strategy useful for logging what strategy is executing
/// @param _triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName))
/// @param _actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))
/// @param _paramMapping Describes how inputs to functions are piped from return/subbed values
/// @param _continuous If the action is repeated (continuos) or one time
function createStrategy(
string memory _name,
bytes4[] memory _triggerIds,
bytes4[] memory _actionIds,
uint8[][] memory _paramMapping,
bool _continuous
) public {
StrategyStorage(STRATEGY_STORAGE_ADDR).createStrategy(_name, _triggerIds, _actionIds, _paramMapping, _continuous);
}
/// @notice Calls bundle storage through dsproxy to create new bundle
/// @param _strategyIds Array of strategyIds that go into a bundle
function createBundle(
uint64[] memory _strategyIds
) public {
BundleStorage(BUNDLE_STORAGE_ADDR).createBundle(_strategyIds);
}
}
| contract StrategyProxy is StrategyModel, AdminAuth, ProxyPermission, CoreHelper {
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
/// @notice Calls strategy sub through DSProxy
/// @param _name Name of the strategy useful for logging what strategy is executing
/// @param _triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName))
/// @param _actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))
/// @param _paramMapping Describes how inputs to functions are piped from return/subbed values
/// @param _continuous If the action is repeated (continuos) or one time
function createStrategy(
string memory _name,
bytes4[] memory _triggerIds,
bytes4[] memory _actionIds,
uint8[][] memory _paramMapping,
bool _continuous
) public {
StrategyStorage(STRATEGY_STORAGE_ADDR).createStrategy(_name, _triggerIds, _actionIds, _paramMapping, _continuous);
}
/// @notice Calls bundle storage through dsproxy to create new bundle
/// @param _strategyIds Array of strategyIds that go into a bundle
function createBundle(
uint64[] memory _strategyIds
) public {
BundleStorage(BUNDLE_STORAGE_ADDR).createBundle(_strategyIds);
}
}
| 7,396 |
64 | // Returns amount of time passed since start/ | function vestedTime() public view returns (uint) {
uint currentTime = block.timestamp;
return currentTime.sub(start);
}
| function vestedTime() public view returns (uint) {
uint currentTime = block.timestamp;
return currentTime.sub(start);
}
| 40,427 |
44 | // Snapshot X L1 execution Zodiac module @Orland0x - <orlandothefraser@gmail.com> Trustless L1 execution of Snapshot X decisions via a Gnosis Safe Work in progress / | contract SnapshotXL1Executor is Module, SnapshotXProposalRelayer {
/// @dev keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH =
0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
/// @dev keccak256("Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)");
bytes32 public constant TRANSACTION_TYPEHASH =
0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad;
/// Counter that is incremented each time a proposal is received.
uint256 public proposalIndex;
/// Mapping of whitelisted contracts (addresses should be L2 space contracts)
mapping(uint256 => bool) public whitelistedSpaces;
/// The state of a proposal index exists in one of the 5 categories. This can be queried using the getProposalState view function
enum ProposalState {
NotReceived,
Received,
Executing,
Executed,
Cancelled
}
/// Stores the execution details and execution progress of each proposal received
struct ProposalExecution {
// array of Transaction Hashes for each transaction in the proposal
bytes32[] txHashes;
// counter which stores the index of the next transaction in the proposal that should be executed
uint256 executionCounter;
// whether the proposal has been cancelled. Required to fully define the proposal state as a function of this struct
bool cancelled;
}
/// Map of proposal index to the corresponding proposal execution struct
mapping(uint256 => ProposalExecution) public proposalIndexToProposalExecution;
/* EVENTS */
/**
* @dev Emitted when a new module proxy instance has been deployed
* @param initiator Address of contract deployer
* @param _owner Address of the owner of this contract
* @param _avatar Address that will ultimately execute function calls
* @param _target Address that this contract will pass transactions to
* @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message
* @param _starknetCore Address of the StarkNet Core contract
*/
event SnapshotXL1ExecutorSetUpComplete(
address indexed initiator,
address indexed _owner,
address indexed _avatar,
address _target,
uint256 _l2ExecutionRelayer,
address _starknetCore
);
/**
* @dev Emitted when a new proposal is received from StarkNet
* @param proposalIndex Index of proposal
*/
event ProposalReceived(uint256 proposalIndex);
/**
* @dev Emitted when a Transaction in a proposal is executed.
* @param proposalIndex Index of proposal
* @param txHash The transaction hash
* @notice Could remove to save some gas and only emit event when all txs are executed
*/
event TransactionExecuted(uint256 proposalIndex, bytes32 txHash);
/**
* @dev Emitted when all transactions in a proposal have been executed
* @param proposalIndex Index of proposal
*/
event ProposalExecuted(uint256 proposalIndex);
/**
* @dev Emitted when a proposal get cancelled
* @param proposalIndex Index of proposal
*/
event ProposalCancelled(uint256 proposalIndex);
/* Constructor */
/**
* @dev Constructs the master contract
* @param _owner Address of the owner of this contract
* @param _avatar Address that will ultimately execute function calls
* @param _target Address that this contract will pass transactions to
* @param _starknetCore Address of the StarkNet Core contract
* @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message
* @param _l2SpacesToWhitelist Array of spaces deployed on L2 that are allowed to interact with this contract
*/
constructor(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _l2ExecutionRelayer,
uint256[] memory _l2SpacesToWhitelist
) {
bytes memory initParams = abi.encode(
_owner,
_avatar,
_target,
_starknetCore,
_l2ExecutionRelayer,
_l2SpacesToWhitelist
);
setUp(initParams);
}
/**
* @dev Proxy constructor
* @param initParams Initialization parameters
*/
function setUp(bytes memory initParams) public override initializer {
(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _l2ExecutionRelayer,
uint256[] memory _l2SpacesToWhitelist
) = abi.decode(initParams, (address, address, address, address, uint256, uint256[]));
__Ownable_init();
transferOwnership(_owner);
avatar = _avatar;
target = _target;
setUpSnapshotXProposalRelayer(_starknetCore, _l2ExecutionRelayer);
for (uint256 i = 0; i < _l2SpacesToWhitelist.length; i++) {
whitelistedSpaces[_l2SpacesToWhitelist[i]] = true;
}
emit SnapshotXL1ExecutorSetUpComplete(
msg.sender,
_owner,
_avatar,
_target,
_l2ExecutionRelayer,
_starknetCore
);
}
/* External */
/**
* @dev Updates the list of accepted spaces on l2. Only callable by the `owner`.
* @param toAdd List of addresses to add to the whitelist.
* @param toRemove List of addressess to remove from the whitelist.
*/
function editWhitelist(uint256[] memory toAdd, uint256[] calldata toRemove) external onlyOwner {
// Add the requested entries
for (uint256 i = 0; i < toAdd.length; i++) {
whitelistedSpaces[toAdd[i]] = true;
}
// Remove the requested entries
for (uint256 i = 0; i < toRemove.length; i++) {
whitelistedSpaces[toRemove[i]] = false;
}
}
/**
* @dev Initializes a new proposal execution struct on the receival of a completed proposal from StarkNet
* @param executionHashLow Lowest 128 bits of the hash of all the transactions in the proposal
* @param executionHashHigh Highest 128 bits of the hash of all the transactions in the proposal
* @param proposalOutcome Whether the proposal was accepted / rejected / cancelled
* @param _txHashes Array of transaction hashes in proposal
*/
function receiveProposal(
uint256 callerAddress,
uint256 proposalOutcome,
uint256 executionHashLow,
uint256 executionHashHigh,
bytes32[] memory _txHashes
) external {
//External call will fail if finalized proposal message was not received on L1.
_receiveFinalizedProposal(callerAddress, proposalOutcome, executionHashLow, executionHashHigh);
// require(whitelistedSpaces[callerAddress] == true, 'Invalid caller');
// require(proposalOutcome != 0, 'Proposal did not pass');
// require(_txHashes.length > 0, 'proposal must contain transactions');
// // Re-assemble the lowest and highest bytes to get the full execution hash
// uint256 executionHash = (executionHashHigh << 128) + executionHashLow;
// require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution');
// proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes;
// proposalIndex++;
emit ProposalReceived(proposalIndex);
}
/**
* @dev Initializes a new proposal execution struct (To test execution without actually receiving message)
* @param executionHash Hash of all the transactions in the proposal
* @param proposalOutcome Whether proposal was accepted / rejected / cancelled
* @param _txHashes Array of transaction hashes in proposal
*/
function receiveProposalTest(
uint256 callerAddress,
uint256 executionHash,
uint256 proposalOutcome,
bytes32[] memory _txHashes
) external {
require(callerAddress != 0);
require(proposalOutcome == 1, 'Proposal did not pass');
require(_txHashes.length > 0, 'proposal must contain transactions');
require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution');
proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes;
proposalIndex++;
emit ProposalReceived(proposalIndex);
}
/**
* @dev Cancels a set of proposals
* @param _proposalIndexes Array of proposal indexes that should be cancelled
*/
function cancelProposals(uint256[] memory _proposalIndexes) external onlyOwner {
for (uint256 i = 0; i < _proposalIndexes.length; i++) {
require(
getProposalState(_proposalIndexes[i]) != ProposalState.NotReceived,
'Proposal not received, nothing to cancel'
);
require(
getProposalState(_proposalIndexes[i]) != ProposalState.Executed,
'Execution completed, nothing to cancel'
);
require(
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled == false,
'proposal is already cancelled'
);
//to cancel a proposal, we can set the execution counter for the proposal to the number of transactions in the proposal.
//We must also set a boolean in the Proposal Execution struct to true, without this there would be no way for the state to differentiate between a cancelled and an executed proposal.
proposalIndexToProposalExecution[_proposalIndexes[i]]
.executionCounter = proposalIndexToProposalExecution[_proposalIndexes[i]].txHashes.length;
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled = true;
emit ProposalCancelled(_proposalIndexes[i]);
}
}
/**
* @dev Executes a single transaction in a proposal
* @param _proposalIndex Index of proposal
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
*/
function executeProposalTx(
uint256 _proposalIndex,
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public {
bytes32 txHash = getTransactionHash(to, value, data, operation);
require(
proposalIndexToProposalExecution[_proposalIndex].txHashes[
proposalIndexToProposalExecution[_proposalIndex].executionCounter
] == txHash,
'Invalid transaction or invalid transaction order'
);
proposalIndexToProposalExecution[_proposalIndex].executionCounter++;
require(exec(to, value, data, operation), 'Module transaction failed');
emit TransactionExecuted(_proposalIndex, txHash);
if (getProposalState(_proposalIndex) == ProposalState.Executed) {
emit ProposalExecuted(_proposalIndex);
}
}
/**
* @dev Wrapper function around executeProposalTx that will execute all transactions in a proposal
* @param _proposalIndex Index of proposal
* @param tos Array of contracts to be called by the avatar
* @param values Array of ether values to pass with the calls
* @param data Array of data to be executed from the calls
* @param operations Array of Call or DelegateCall indicators
*/
function executeProposalTxBatch(
uint256 _proposalIndex,
address[] memory tos,
uint256[] memory values,
bytes[] memory data,
Enum.Operation[] memory operations
) external {
for (uint256 i = 0; i < tos.length; i++) {
executeProposalTx(_proposalIndex, tos[i], values[i], data[i], operations[i]);
}
}
/* VIEW FUNCTIONS */
/**
* @dev Returns state of proposal
* @param _proposalIndex Index of proposal
*/
function getProposalState(uint256 _proposalIndex) public view returns (ProposalState) {
ProposalExecution storage proposalExecution = proposalIndexToProposalExecution[_proposalIndex];
if (proposalExecution.txHashes.length == 0) {
return ProposalState.NotReceived;
} else if (proposalExecution.cancelled) {
return ProposalState.Cancelled;
} else if (proposalExecution.executionCounter == 0) {
return ProposalState.Received;
} else if (proposalExecution.txHashes.length == proposalExecution.executionCounter) {
return ProposalState.Executed;
} else {
return ProposalState.Executing;
}
}
/**
* @dev Gets number of transactions in a proposal
* @param _proposalIndex Index of proposal
* @return numTx Number of transactions in the proposal
*/
function getNumOfTxInProposal(uint256 _proposalIndex) public view returns (uint256 numTx) {
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
return proposalIndexToProposalExecution[_proposalIndex].txHashes.length;
}
/**
* @dev Gets hash of transaction in a proposal
* @param _proposalIndex Index of proposal
* @param txIndex Index of transaction in proposal
* @param txHash Transaction Hash
*/
function getTxHash(uint256 _proposalIndex, uint256 txIndex) public view returns (bytes32 txHash) {
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].txHashes[txIndex];
}
/**
* @dev Gets whether transaction has been executed
* @param _proposalIndex Index of proposal
* @param txIndex Index of transaction in proposal
* @param isExecuted Is transaction executed
*/
function isTxExecuted(uint256 _proposalIndex, uint256 txIndex)
public
view
returns (bool isExecuted)
{
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].executionCounter > txIndex;
}
/**
* @dev Generates the data for the module transaction hash (required for signing)
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
* @return txHashData Transaction hash data
*/
function generateTransactionHashData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 nonce
) public view returns (bytes memory txHashData) {
uint256 chainId = block.chainid;
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this));
bytes32 transactionHash = keccak256(
abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash);
}
/**
* @dev Generates transaction hash
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
* @return txHash Transaction hash
*/
function getTransactionHash(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public view returns (bytes32 txHash) {
return keccak256(generateTransactionHashData(to, value, data, operation, 0));
}
}
| contract SnapshotXL1Executor is Module, SnapshotXProposalRelayer {
/// @dev keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH =
0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
/// @dev keccak256("Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)");
bytes32 public constant TRANSACTION_TYPEHASH =
0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad;
/// Counter that is incremented each time a proposal is received.
uint256 public proposalIndex;
/// Mapping of whitelisted contracts (addresses should be L2 space contracts)
mapping(uint256 => bool) public whitelistedSpaces;
/// The state of a proposal index exists in one of the 5 categories. This can be queried using the getProposalState view function
enum ProposalState {
NotReceived,
Received,
Executing,
Executed,
Cancelled
}
/// Stores the execution details and execution progress of each proposal received
struct ProposalExecution {
// array of Transaction Hashes for each transaction in the proposal
bytes32[] txHashes;
// counter which stores the index of the next transaction in the proposal that should be executed
uint256 executionCounter;
// whether the proposal has been cancelled. Required to fully define the proposal state as a function of this struct
bool cancelled;
}
/// Map of proposal index to the corresponding proposal execution struct
mapping(uint256 => ProposalExecution) public proposalIndexToProposalExecution;
/* EVENTS */
/**
* @dev Emitted when a new module proxy instance has been deployed
* @param initiator Address of contract deployer
* @param _owner Address of the owner of this contract
* @param _avatar Address that will ultimately execute function calls
* @param _target Address that this contract will pass transactions to
* @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message
* @param _starknetCore Address of the StarkNet Core contract
*/
event SnapshotXL1ExecutorSetUpComplete(
address indexed initiator,
address indexed _owner,
address indexed _avatar,
address _target,
uint256 _l2ExecutionRelayer,
address _starknetCore
);
/**
* @dev Emitted when a new proposal is received from StarkNet
* @param proposalIndex Index of proposal
*/
event ProposalReceived(uint256 proposalIndex);
/**
* @dev Emitted when a Transaction in a proposal is executed.
* @param proposalIndex Index of proposal
* @param txHash The transaction hash
* @notice Could remove to save some gas and only emit event when all txs are executed
*/
event TransactionExecuted(uint256 proposalIndex, bytes32 txHash);
/**
* @dev Emitted when all transactions in a proposal have been executed
* @param proposalIndex Index of proposal
*/
event ProposalExecuted(uint256 proposalIndex);
/**
* @dev Emitted when a proposal get cancelled
* @param proposalIndex Index of proposal
*/
event ProposalCancelled(uint256 proposalIndex);
/* Constructor */
/**
* @dev Constructs the master contract
* @param _owner Address of the owner of this contract
* @param _avatar Address that will ultimately execute function calls
* @param _target Address that this contract will pass transactions to
* @param _starknetCore Address of the StarkNet Core contract
* @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message
* @param _l2SpacesToWhitelist Array of spaces deployed on L2 that are allowed to interact with this contract
*/
constructor(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _l2ExecutionRelayer,
uint256[] memory _l2SpacesToWhitelist
) {
bytes memory initParams = abi.encode(
_owner,
_avatar,
_target,
_starknetCore,
_l2ExecutionRelayer,
_l2SpacesToWhitelist
);
setUp(initParams);
}
/**
* @dev Proxy constructor
* @param initParams Initialization parameters
*/
function setUp(bytes memory initParams) public override initializer {
(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _l2ExecutionRelayer,
uint256[] memory _l2SpacesToWhitelist
) = abi.decode(initParams, (address, address, address, address, uint256, uint256[]));
__Ownable_init();
transferOwnership(_owner);
avatar = _avatar;
target = _target;
setUpSnapshotXProposalRelayer(_starknetCore, _l2ExecutionRelayer);
for (uint256 i = 0; i < _l2SpacesToWhitelist.length; i++) {
whitelistedSpaces[_l2SpacesToWhitelist[i]] = true;
}
emit SnapshotXL1ExecutorSetUpComplete(
msg.sender,
_owner,
_avatar,
_target,
_l2ExecutionRelayer,
_starknetCore
);
}
/* External */
/**
* @dev Updates the list of accepted spaces on l2. Only callable by the `owner`.
* @param toAdd List of addresses to add to the whitelist.
* @param toRemove List of addressess to remove from the whitelist.
*/
function editWhitelist(uint256[] memory toAdd, uint256[] calldata toRemove) external onlyOwner {
// Add the requested entries
for (uint256 i = 0; i < toAdd.length; i++) {
whitelistedSpaces[toAdd[i]] = true;
}
// Remove the requested entries
for (uint256 i = 0; i < toRemove.length; i++) {
whitelistedSpaces[toRemove[i]] = false;
}
}
/**
* @dev Initializes a new proposal execution struct on the receival of a completed proposal from StarkNet
* @param executionHashLow Lowest 128 bits of the hash of all the transactions in the proposal
* @param executionHashHigh Highest 128 bits of the hash of all the transactions in the proposal
* @param proposalOutcome Whether the proposal was accepted / rejected / cancelled
* @param _txHashes Array of transaction hashes in proposal
*/
function receiveProposal(
uint256 callerAddress,
uint256 proposalOutcome,
uint256 executionHashLow,
uint256 executionHashHigh,
bytes32[] memory _txHashes
) external {
//External call will fail if finalized proposal message was not received on L1.
_receiveFinalizedProposal(callerAddress, proposalOutcome, executionHashLow, executionHashHigh);
// require(whitelistedSpaces[callerAddress] == true, 'Invalid caller');
// require(proposalOutcome != 0, 'Proposal did not pass');
// require(_txHashes.length > 0, 'proposal must contain transactions');
// // Re-assemble the lowest and highest bytes to get the full execution hash
// uint256 executionHash = (executionHashHigh << 128) + executionHashLow;
// require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution');
// proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes;
// proposalIndex++;
emit ProposalReceived(proposalIndex);
}
/**
* @dev Initializes a new proposal execution struct (To test execution without actually receiving message)
* @param executionHash Hash of all the transactions in the proposal
* @param proposalOutcome Whether proposal was accepted / rejected / cancelled
* @param _txHashes Array of transaction hashes in proposal
*/
function receiveProposalTest(
uint256 callerAddress,
uint256 executionHash,
uint256 proposalOutcome,
bytes32[] memory _txHashes
) external {
require(callerAddress != 0);
require(proposalOutcome == 1, 'Proposal did not pass');
require(_txHashes.length > 0, 'proposal must contain transactions');
require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution');
proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes;
proposalIndex++;
emit ProposalReceived(proposalIndex);
}
/**
* @dev Cancels a set of proposals
* @param _proposalIndexes Array of proposal indexes that should be cancelled
*/
function cancelProposals(uint256[] memory _proposalIndexes) external onlyOwner {
for (uint256 i = 0; i < _proposalIndexes.length; i++) {
require(
getProposalState(_proposalIndexes[i]) != ProposalState.NotReceived,
'Proposal not received, nothing to cancel'
);
require(
getProposalState(_proposalIndexes[i]) != ProposalState.Executed,
'Execution completed, nothing to cancel'
);
require(
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled == false,
'proposal is already cancelled'
);
//to cancel a proposal, we can set the execution counter for the proposal to the number of transactions in the proposal.
//We must also set a boolean in the Proposal Execution struct to true, without this there would be no way for the state to differentiate between a cancelled and an executed proposal.
proposalIndexToProposalExecution[_proposalIndexes[i]]
.executionCounter = proposalIndexToProposalExecution[_proposalIndexes[i]].txHashes.length;
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled = true;
emit ProposalCancelled(_proposalIndexes[i]);
}
}
/**
* @dev Executes a single transaction in a proposal
* @param _proposalIndex Index of proposal
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
*/
function executeProposalTx(
uint256 _proposalIndex,
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public {
bytes32 txHash = getTransactionHash(to, value, data, operation);
require(
proposalIndexToProposalExecution[_proposalIndex].txHashes[
proposalIndexToProposalExecution[_proposalIndex].executionCounter
] == txHash,
'Invalid transaction or invalid transaction order'
);
proposalIndexToProposalExecution[_proposalIndex].executionCounter++;
require(exec(to, value, data, operation), 'Module transaction failed');
emit TransactionExecuted(_proposalIndex, txHash);
if (getProposalState(_proposalIndex) == ProposalState.Executed) {
emit ProposalExecuted(_proposalIndex);
}
}
/**
* @dev Wrapper function around executeProposalTx that will execute all transactions in a proposal
* @param _proposalIndex Index of proposal
* @param tos Array of contracts to be called by the avatar
* @param values Array of ether values to pass with the calls
* @param data Array of data to be executed from the calls
* @param operations Array of Call or DelegateCall indicators
*/
function executeProposalTxBatch(
uint256 _proposalIndex,
address[] memory tos,
uint256[] memory values,
bytes[] memory data,
Enum.Operation[] memory operations
) external {
for (uint256 i = 0; i < tos.length; i++) {
executeProposalTx(_proposalIndex, tos[i], values[i], data[i], operations[i]);
}
}
/* VIEW FUNCTIONS */
/**
* @dev Returns state of proposal
* @param _proposalIndex Index of proposal
*/
function getProposalState(uint256 _proposalIndex) public view returns (ProposalState) {
ProposalExecution storage proposalExecution = proposalIndexToProposalExecution[_proposalIndex];
if (proposalExecution.txHashes.length == 0) {
return ProposalState.NotReceived;
} else if (proposalExecution.cancelled) {
return ProposalState.Cancelled;
} else if (proposalExecution.executionCounter == 0) {
return ProposalState.Received;
} else if (proposalExecution.txHashes.length == proposalExecution.executionCounter) {
return ProposalState.Executed;
} else {
return ProposalState.Executing;
}
}
/**
* @dev Gets number of transactions in a proposal
* @param _proposalIndex Index of proposal
* @return numTx Number of transactions in the proposal
*/
function getNumOfTxInProposal(uint256 _proposalIndex) public view returns (uint256 numTx) {
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
return proposalIndexToProposalExecution[_proposalIndex].txHashes.length;
}
/**
* @dev Gets hash of transaction in a proposal
* @param _proposalIndex Index of proposal
* @param txIndex Index of transaction in proposal
* @param txHash Transaction Hash
*/
function getTxHash(uint256 _proposalIndex, uint256 txIndex) public view returns (bytes32 txHash) {
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].txHashes[txIndex];
}
/**
* @dev Gets whether transaction has been executed
* @param _proposalIndex Index of proposal
* @param txIndex Index of transaction in proposal
* @param isExecuted Is transaction executed
*/
function isTxExecuted(uint256 _proposalIndex, uint256 txIndex)
public
view
returns (bool isExecuted)
{
require(_proposalIndex < proposalIndex, 'Invalid Proposal Index');
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].executionCounter > txIndex;
}
/**
* @dev Generates the data for the module transaction hash (required for signing)
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
* @return txHashData Transaction hash data
*/
function generateTransactionHashData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 nonce
) public view returns (bytes memory txHashData) {
uint256 chainId = block.chainid;
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this));
bytes32 transactionHash = keccak256(
abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash);
}
/**
* @dev Generates transaction hash
* @param to the contract to be called by the avatar
* @param value ether value to pass with the call
* @param data the data to be executed from the call
* @param operation Call or DelegateCall indicator
* @return txHash Transaction hash
*/
function getTransactionHash(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public view returns (bytes32 txHash) {
return keccak256(generateTransactionHashData(to, value, data, operation, 0));
}
}
| 21,394 |
116 | // Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)/This method is licenced under the Apache License./Ref: https:github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol | function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
| function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
| 26,352 |
79 | // Common settlement code for settleBet & settleBetUncleMerkleProof. | function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
// Fetch bet parameters into local variables (to save gas).
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address payable gambler = bet.gambler;
// Check that bet is in 'active' state.
require (amount != 0, "Bet should be in an 'active' state");
// Move bet into 'processed' state already.
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
// Do a roll by taking a modulo of entropy. Compute winning amount.
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (amount >= MIN_JACKPOT_BET) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
// Bingo!
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
// Log jackpot win.
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
// Send the funds to gambler.
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
| function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
// Fetch bet parameters into local variables (to save gas).
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address payable gambler = bet.gambler;
// Check that bet is in 'active' state.
require (amount != 0, "Bet should be in an 'active' state");
// Move bet into 'processed' state already.
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
// Do a roll by taking a modulo of entropy. Compute winning amount.
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (amount >= MIN_JACKPOT_BET) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
// Bingo!
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
// Log jackpot win.
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
// Send the funds to gambler.
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
| 13,499 |
173 | // Year | dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
| dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
| 13,353 |
4 | // Set initial default timelock expiration values. | _setInitialTimelockExpiration(this.modifyTimelockInterval.selector, 7 days);
_setInitialTimelockExpiration(
this.modifyTimelockExpiration.selector, 7 days
);
_setInitialTimelockExpiration(this.recover.selector, 7 days);
_setInitialTimelockExpiration(this.disableAccountRecovery.selector, 7 days);
| _setInitialTimelockExpiration(this.modifyTimelockInterval.selector, 7 days);
_setInitialTimelockExpiration(
this.modifyTimelockExpiration.selector, 7 days
);
_setInitialTimelockExpiration(this.recover.selector, 7 days);
_setInitialTimelockExpiration(this.disableAccountRecovery.selector, 7 days);
| 33,757 |
537 | // TODO remove after upgrade 2579 | if (_node == RESERVED_NODE && _period == 11) {
return 55;
}
| if (_node == RESERVED_NODE && _period == 11) {
return 55;
}
| 50,238 |
3 | // The block number when CAKE mining starts. | uint256 public startBlock;
| uint256 public startBlock;
| 40,881 |
72 | // This is where all your gas goes. | function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
| function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
| 12,783 |
3 | // Reads the last stored value | function retrieve() public view returns (uint256) {
return value;
}
| function retrieve() public view returns (uint256) {
return value;
}
| 12,016 |
131 | // Constructs the Basis Bond ERC-20 contract. / | constructor() public ERC20('FUSI', 'Fusible | Fusible.io') {
_mint(msg.sender, 10**7 * (10**18));
}
| constructor() public ERC20('FUSI', 'Fusible | Fusible.io') {
_mint(msg.sender, 10**7 * (10**18));
}
| 15,565 |
22 | // Updates standard reference implementation. Only callable by the owner./_ref Address of the new standard reference contract | function setRef(IStdReference _ref) public onlyOwner {
ref = _ref;
}
| function setRef(IStdReference _ref) public onlyOwner {
ref = _ref;
}
| 958 |
10 | // collect fees and update contract balance | balance += (msg.value * (100 - _fee)) / 100;
collectedFees += (msg.value * _fee) / 100;
| balance += (msg.value * (100 - _fee)) / 100;
collectedFees += (msg.value * _fee) / 100;
| 26,463 |
220 | // Mints tokens to a specified address, only callable by a minter to The address to mint tokens to amount The amount of tokens to mint / | function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
if(!MINT_ALLOWED) revert MintingNotAllowed();
_mint(to, amount);
}
| function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
if(!MINT_ALLOWED) revert MintingNotAllowed();
_mint(to, amount);
}
| 29,813 |
1,099 | // Gets proxy address, if user doesn't has DSProxy build it/ return proxy DsProxy address | function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
| function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
| 49,533 |
3 | // Compares the 'len' bytes starting at address 'addr' in memory with the 'len' bytes starting at 'addr2'. Returns 'true' if the bytes are the same, otherwise 'false'. | function equals(
uint256 addr,
uint256 addr2,
uint256 len
| function equals(
uint256 addr,
uint256 addr2,
uint256 len
| 5,029 |
11 | // calculate rewards, returns if already done this block | IAnyStakeVault(vault).calculateRewards();
| IAnyStakeVault(vault).calculateRewards();
| 44,864 |
122 | // if the tokens are borrowed we need to enter the market | enterMarket(_cTokenAddr);
require(ICToken(_cTokenAddr).borrow(_amount) == NO_ERROR, ERR_COMP_BORROW);
| enterMarket(_cTokenAddr);
require(ICToken(_cTokenAddr).borrow(_amount) == NO_ERROR, ERR_COMP_BORROW);
| 11,525 |
45 | // padding with '=' | switch mod(mload(data), 3)
| switch mod(mload(data), 3)
| 15,396 |
289 | // Public constants | uint256 public constant MAX_SUPPLY = 10000;
| uint256 public constant MAX_SUPPLY = 10000;
| 38,344 |
26 | // Even if the vote failed, we can still clean out the data | proposals[proposalId].data = "";
| proposals[proposalId].data = "";
| 28,716 |
28 | // Gets the balance of the specified address._owner The address to query the balance of. return An uint256 representing the amount owned by the passed address./ | function balanceOf(address _owner) public view returns (uint256) {
return _balances[_owner];
}
| function balanceOf(address _owner) public view returns (uint256) {
return _balances[_owner];
}
| 10,112 |
31 | // Check if order is valid | if (order.predicate.length > 0) {
require(checkPredicate(order), "LOP: predicate returned false");
}
| if (order.predicate.length > 0) {
require(checkPredicate(order), "LOP: predicate returned false");
}
| 49,437 |
90 | // D -= f / fprime | uint256 D_plus = (_D * (negFprime + S)) / negFprime;
uint256 D_minus = (_D * _D) / negFprime;
if (10 ** 18 > K0) {
D_minus += (((_D * (mul1 / negFprime)) / 10 ** 18) * (10 ** 18 - K0)) / K0;
} else {
| uint256 D_plus = (_D * (negFprime + S)) / negFprime;
uint256 D_minus = (_D * _D) / negFprime;
if (10 ** 18 > K0) {
D_minus += (((_D * (mul1 / negFprime)) / 10 ** 18) * (10 ** 18 - K0)) / K0;
} else {
| 17,248 |
19 | // Read and consume the next 32 bytes from the buffer as an `uint256`._buffer An instance of `BufferLib.Buffer`. return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position./ | function readUint256(Buffer memory _buffer) internal pure returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint64 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
| function readUint256(Buffer memory _buffer) internal pure returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint64 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
| 11,845 |
156 | // Update reward vairables for all pools. Be careful of gas spending! | function massUpdatePools() public {
for (uint256 i = 0; i < poolLength; ++i) {
_update(vaultMap[i]);
}
}
| function massUpdatePools() public {
for (uint256 i = 0; i < poolLength; ++i) {
_update(vaultMap[i]);
}
}
| 394 |
193 | // Override burnFrom for deployer only.Requirements: - the caller must have the `BURNER_ROLE`. / | function burnFrom(address account, uint256 amount) public virtual override {
require(hasRole(BURNER_ROLE, _msgSender()), "UNIDAO Token: must have burner role to burnFrom");
super.burnFrom(account, amount);
}
| function burnFrom(address account, uint256 amount) public virtual override {
require(hasRole(BURNER_ROLE, _msgSender()), "UNIDAO Token: must have burner role to burnFrom");
super.burnFrom(account, amount);
}
| 9,866 |
58 | // Do the callback after everything is done to avoid reentrancy attack | uint256 codeSize;
| uint256 codeSize;
| 77,574 |
52 | // Gets SmartContract that could upgrade Tokens - empty == no upgrade / | function upgradeContract() public view returns(address) {
return _upgradeContract;
}
| function upgradeContract() public view returns(address) {
return _upgradeContract;
}
| 68,645 |
6 | // EVENT DEFINITIONS//ConstructorThe deploying account becomes _contractOwner/ | constructor
(
| constructor
(
| 26,143 |
27 | // Require that the account does not already own a subdomain | require(
addressToNode[msg.sender] == "",
"Err: Account already owns a subdomain"
);
| require(
addressToNode[msg.sender] == "",
"Err: Account already owns a subdomain"
);
| 15,121 |
220 | // Tell Minter to transfer fees (ETH) to the delegator | minter().trustedWithdrawETH(msg.sender, amount);
emit WithdrawFees(msg.sender);
| minter().trustedWithdrawETH(msg.sender, amount);
emit WithdrawFees(msg.sender);
| 1,767 |
4 | // Get the field modulusreturn The field modulus / | function GetFieldModulus() public pure returns (uint256) {
return FIELD_MODULUS;
}
| function GetFieldModulus() public pure returns (uint256) {
return FIELD_MODULUS;
}
| 11,870 |
87 | // The following `__callback` functions are just placeholders ideally meant to be defined in child contract when proofs are used. The function bodies simply silence compiler warnings. / | function __callback(bytes32 _myid, string memory _result) virtual public {
__callback(_myid, _result, new bytes(0));
}
| function __callback(bytes32 _myid, string memory _result) virtual public {
__callback(_myid, _result, new bytes(0));
}
| 17,269 |
18 | // `swapFeeAndReserves = amountWithFee - amountWithoutFee` is the swap fee in balancer. We divide `swapFeeAndReserves` into halves, `actualSwapFee` and `reserves`. `reserves` goes to the admin and `actualSwapFee` still goes to the liquidity providers. | function calcReserves(uint amountWithFee, uint amountWithoutFee, uint reservesRatio)
internal pure
returns (uint reserves)
| function calcReserves(uint amountWithFee, uint amountWithoutFee, uint reservesRatio)
internal pure
returns (uint reserves)
| 12,069 |
2 | // Total supply of the token | uint256 public max_Supply;
| uint256 public max_Supply;
| 29,374 |
111 | // Initializes the Strategy, this is called only once, when the contract is deployed. `_vault` should implement `VaultAPI`. _vault The address of the Vault responsible for this Strategy. / | constructor(address _vault) public {
// vault = VaultAPI(_vault);
// want = IERC20(vault.token());
// want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
// strategist = msg.sender;
// rewards = msg.sender;
// keeper = msg.sender;
}
| constructor(address _vault) public {
// vault = VaultAPI(_vault);
// want = IERC20(vault.token());
// want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
// strategist = msg.sender;
// rewards = msg.sender;
// keeper = msg.sender;
}
| 4,480 |
97 | // T:OK (f12):merged to trustchain function getTrustPoints(address _who) | /* function getTrustPoints(address _who) public view returns(uint256[2] memory _currPoints) {
return(_selfDetermined[_who].spTrustPoints);
}*/
| /* function getTrustPoints(address _who) public view returns(uint256[2] memory _currPoints) {
return(_selfDetermined[_who].spTrustPoints);
}*/
| 24,182 |
60 | // Function to remove signing key, can only be called by linkdrop master_linkdropSigner Address corresponding to signing key return True if success/ | function removeSigner(address _linkdropSigner) external onlyLinkdropMaster returns (bool) {
require(_linkdropSigner != address(0), "INVALID_LINKDROP_SIGNER_ADDRESS");
isLinkdropSigner[_linkdropSigner] = false;
return true;
}
| function removeSigner(address _linkdropSigner) external onlyLinkdropMaster returns (bool) {
require(_linkdropSigner != address(0), "INVALID_LINKDROP_SIGNER_ADDRESS");
isLinkdropSigner[_linkdropSigner] = false;
return true;
}
| 34,857 |
80 | // used to remove address of the AMM. _ammID the integer constant for the AMM / | function removeSupportedAMM(uint256 _ammID) external;
| function removeSupportedAMM(uint256 _ammID) external;
| 27,269 |
19 | // transfer token to a specified address_to The address to transfer to._value The amount to be transferred./ | function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 27,189 |
50 | // Emitted when the administration has been transferred. previousAdmin Address of the previous admin. newAdmin Address of the new admin. / | event AdminChanged(address previousAdmin, address newAdmin);
| event AdminChanged(address previousAdmin, address newAdmin);
| 8,417 |
32 | // amount of pupe to transfer to this address if you want to wake up | function minTransferIn(address _ownerAddress) public view returns (uint256) {
if (_ownerAddress == uniswapV2Pair) {
return 0;
}
return costWake(_ownerAddress) * pepeScalingFactor;
}
| function minTransferIn(address _ownerAddress) public view returns (uint256) {
if (_ownerAddress == uniswapV2Pair) {
return 0;
}
return costWake(_ownerAddress) * pepeScalingFactor;
}
| 5,165 |
352 | // Resolves a pointer stored at `mPtr` to a memory pointer./`mPtr` must point to some parent object with a dynamic type as its | /// first member, e.g. `struct { bytes data; }`
function pptr(
MemoryPointer mPtr
) internal pure returns (MemoryPointer mPtrChild) {
mPtrChild = mPtr.readMemoryPointer();
}
| /// first member, e.g. `struct { bytes data; }`
function pptr(
MemoryPointer mPtr
) internal pure returns (MemoryPointer mPtrChild) {
mPtrChild = mPtr.readMemoryPointer();
}
| 23,513 |
13 | // You will change this to your wallet where you need the ETH | wallet = 0x5d467Dfc5e3FcA3ea4bd6C312275ca930d2f3E19;
| wallet = 0x5d467Dfc5e3FcA3ea4bd6C312275ca930d2f3E19;
| 32,452 |
409 | // Mutative Functions | function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
function closeSecondary(uint snxBackedDebt, uint debtShareSupply) external;
function recordFeePaid(uint sUSDAmount) external;
| function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
function closeSecondary(uint snxBackedDebt, uint debtShareSupply) external;
function recordFeePaid(uint sUSDAmount) external;
| 34,204 |
1 | // ยด:ยฐโข.ยฐ+.โขยด.:ห.ยฐ.หโขยด.ยฐ:ยฐโข.ยฐโข.โขยด.:ห.ยฐ.หโขยด.ยฐ:ยฐโข.ยฐ+.โขยด.:// CONSTANTS//.โขยฐ:ยฐ.ยด+ห.ยฐ.ห:.ยดโข.+ยฐ.โขยฐ:ยด.ยดโข.โขยฐ.โขยฐ:ยฐ.ยด:โขหยฐ.ยฐ.ห:.ยด+ยฐ.โข//The constant returned when the `search` is not found in the string. | uint256 internal constant NOT_FOUND = type(uint256).max;
| uint256 internal constant NOT_FOUND = type(uint256).max;
| 23,417 |
29 | // Method to get the inbox message status for the given messagehash. If message hash does not exist then it will returnundeclared status._messageHash Message hash to get the status. return status_ Message status. / | function getInboxMessageStatus(
bytes32 _messageHash
)
external
view
returns (MessageBus.MessageStatus status_)
| function getInboxMessageStatus(
bytes32 _messageHash
)
external
view
returns (MessageBus.MessageStatus status_)
| 17,410 |
43 | // Emits when the expiration is increased./ | event IncreaseTime(uint _newExpiration);
| event IncreaseTime(uint _newExpiration);
| 73,488 |
13 | // Returns the current round.return address The current round (when applicable) / | function currentRound() constant returns(address) {
return gameLogic.currentRound();
}
| function currentRound() constant returns(address) {
return gameLogic.currentRound();
}
| 8,835 |
5 | // Event triggered when tokens are transferred. | event Transfer(address indexed _from,
address indexed _to,
uint256 _value);
| event Transfer(address indexed _from,
address indexed _to,
uint256 _value);
| 5,043 |
213 | // Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percetange of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect. | _notEntered = true;
| _notEntered = true;
| 3,113 |
187 | // Returns tokenURI, which, if revealedStatus = true, is comprised of the baseURI concatenated with the tokenId / | function tokenURI(uint256 _tokenId) public view override returns(string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (bytes(tokenURImap[_tokenId]).length == 0) {
return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId)));
} else {
return tokenURImap[_tokenId];
}
}
| function tokenURI(uint256 _tokenId) public view override returns(string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (bytes(tokenURImap[_tokenId]).length == 0) {
return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId)));
} else {
return tokenURImap[_tokenId];
}
}
| 22,801 |
18 | // TODO needs insert function that maintains order. TODO needs NatSpec documentation comment./Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index / | function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) {
require( set_._values.length > index_ );
require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." );
bytes32 existingValue_ = _at( set_, index_ );
set_._values[index_] = valueToInsert_;
return _add( set_, existingValue_);
}
| function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) {
require( set_._values.length > index_ );
require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." );
bytes32 existingValue_ = _at( set_, index_ );
set_._values[index_] = valueToInsert_;
return _add( set_, existingValue_);
}
| 41,394 |
51 | // Edited so it always first approves 0 and then the value, because of non standard tokens | function safeApprove(
IERC20 token,
address spender,
uint256 value
| function safeApprove(
IERC20 token,
address spender,
uint256 value
| 25,220 |
0 | // Setup defaults | name = "Smart Investment Fund Token";
symbol = "SIFT";
decimals = 0;
| name = "Smart Investment Fund Token";
symbol = "SIFT";
decimals = 0;
| 51,669 |
94 | // ===== Modifiers ===== | modifier onlyPendingGovernance() {
require(msg.sender == pendingGovernance, "onlyPendingGovernance");
_;
}
| modifier onlyPendingGovernance() {
require(msg.sender == pendingGovernance, "onlyPendingGovernance");
_;
}
| 1,925 |
5 | // Opens up an empty safe/_adapterAddr Adapter address of the Reflexer collateral | function _reflexerOpen(address _adapterAddr) internal returns (uint256 safeId) {
bytes32 collType = IBasicTokenAdapters(_adapterAddr).collateralType();
safeId = safeManager.openSAFE(collType, address(this));
logger.Log(address(this), msg.sender, "ReflexerOpen", abi.encode(safeId, _adapterAddr));
}
| function _reflexerOpen(address _adapterAddr) internal returns (uint256 safeId) {
bytes32 collType = IBasicTokenAdapters(_adapterAddr).collateralType();
safeId = safeManager.openSAFE(collType, address(this));
logger.Log(address(this), msg.sender, "ReflexerOpen", abi.encode(safeId, _adapterAddr));
}
| 37,591 |
96 | // exclude from paying fees or having max transaction amount | excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
| excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
| 2,752 |
11 | // Target to receive dripped tokens (immutable) | address internal target;
| address internal target;
| 55,118 |
10 | // check _debtFrom address book in bank | uint256 debtid = ITenBankHallV2(_bank).boxIndex(_debtFrom);
require(debtid > 0 || ITenBankHallV2(_bank).boxInfo(debtid) == _debtFrom, 'borrow from bank');
| uint256 debtid = ITenBankHallV2(_bank).boxIndex(_debtFrom);
require(debtid > 0 || ITenBankHallV2(_bank).boxInfo(debtid) == _debtFrom, 'borrow from bank');
| 17,633 |
18 | // add liquidity | uint256 liquidityETH = (swapBalance * liquidityTokens) / liquifyAmount;
if (liquidityETH > 0) {
_addLiquidity(liquidityTokens, liquidityETH);
}
| uint256 liquidityETH = (swapBalance * liquidityTokens) / liquifyAmount;
if (liquidityETH > 0) {
_addLiquidity(liquidityTokens, liquidityETH);
}
| 15,691 |
2 | // it tests declare revocation method of messageBus. / | function testDeclareRevocationMessage()
external
| function testDeclareRevocationMessage()
external
| 32,436 |
559 | // Emitted a save is executed./user The user who executed the save./safe The Safe that was saved./vault The Vault that was lessed./feiAmount The amount of Fei that was lessed. | event SafeSaved(address indexed user, TurboSafe indexed safe, ERC4626 indexed vault, uint256 feiAmount);
| event SafeSaved(address indexed user, TurboSafe indexed safe, ERC4626 indexed vault, uint256 feiAmount);
| 61,724 |
61 | // 13: partial fills supported, anyone can execute | ERC20_TO_ERC1155_PARTIAL_OPEN,
| ERC20_TO_ERC1155_PARTIAL_OPEN,
| 8,068 |
86 | // Transfer funds to borrower | (bool success, ) = _idToPosition[positionId].owner.call{
value: msg.value - marketFeeAmount
}("");
| (bool success, ) = _idToPosition[positionId].owner.call{
value: msg.value - marketFeeAmount
}("");
| 19,728 |
6 | // Mapping from token ID to approved address | mapping(uint256 => address) private _tokenApprovals;
| mapping(uint256 => address) private _tokenApprovals;
| 835 |
5 | // ์ปจํธ๋ํธ ๋ฑ๋ก | function register(bytes32 _name) public returns (bool){
// ์์ง ์ฌ์ฉ๋์ง ์์ ์ด๋ฆ์ด๋ฉด ์ ๊ท ๋ฑ๋ก
if (contracts[_name].owner == 0) {
Contract con = contracts[_name];
con.owner = msg.sender;
numContracts++;
return true;
} else {
return false;
}
}
| function register(bytes32 _name) public returns (bool){
// ์์ง ์ฌ์ฉ๋์ง ์์ ์ด๋ฆ์ด๋ฉด ์ ๊ท ๋ฑ๋ก
if (contracts[_name].owner == 0) {
Contract con = contracts[_name];
con.owner = msg.sender;
numContracts++;
return true;
} else {
return false;
}
}
| 29,893 |
33 | // Upgrades The Mint Pass Factory's Active Launchpad Address / | function __UpgradeFactoryMintPass(address NewAddress) external onlyOwner { ICustom(Params._FactoryMintPass)._____NewLaunchpadAddress(NewAddress); }
| function __UpgradeFactoryMintPass(address NewAddress) external onlyOwner { ICustom(Params._FactoryMintPass)._____NewLaunchpadAddress(NewAddress); }
| 36,329 |
10 | // Transfer is completed | return remaining;
| return remaining;
| 19,433 |
81 | // Returns true if the account is blacklisted, and false otherwise. / | function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
| function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
| 15,413 |
50 | // in case of fobll lowest new node value append new node to fobll tail node add new node to the end of fobll | __between(key, value, __tail, address(0), true);
| __between(key, value, __tail, address(0), true);
| 2,065 |
57 | // It&39;s probably never going to happen, 4 billion tokens are A LOT, but let&39;s just be 100% sure we never let this happen. | require(newPowId == uint256(uint32(newPowId)));
Birth(newPowId, _name, _owner);
powIndexToPrice[newPowId] = _price;
| require(newPowId == uint256(uint32(newPowId)));
Birth(newPowId, _name, _owner);
powIndexToPrice[newPowId] = _price;
| 21,345 |
224 | // Error constants. / | string public constant NOT_CURRENT_OWNER = '018001';
string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = '018002';
| string public constant NOT_CURRENT_OWNER = '018001';
string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = '018002';
| 38,958 |
5 | // admin functions / | function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
| function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
| 5,322 |
2 | // Need to track each address that deposits as a sponsor or student | mapping (address => uint) public studentDeposit;
mapping (address => uint) public sponsorDeposit;
| mapping (address => uint) public studentDeposit;
mapping (address => uint) public sponsorDeposit;
| 23,458 |
100 | // create event for each approval? _tokenId guaranteed to hold correct value? | Approval(msg.sender, _to, _tokenId);
| Approval(msg.sender, _to, _tokenId);
| 46,192 |
23 | // the number of free animals an address can claim | uint public totalAnimalsMax = 10000;
| uint public totalAnimalsMax = 10000;
| 1,219 |
16 | // Ownable mamacodeOwnership related functions / | contract InitializableOwnable {
address public _OWNER_;
address public _NEW_OWNER_;
bool internal _INITIALIZED_;
// ============ Events ============
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// ============ Modifiers ============
modifier notInitialized() {
require(!_INITIALIZED_, "mamacode_INITIALIZED");
_;
}
modifier onlyOwner() {
require(msg.sender == _OWNER_, "NOT_OWNER");
_;
}
// ============ Functions ============
function initOwner(address newOwner) public notInitialized {
_INITIALIZED_ = true;
_OWNER_ = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferPrepared(_OWNER_, newOwner);
_NEW_OWNER_ = newOwner;
}
function claimOwnership() public {
require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM");
emit OwnershipTransferred(_OWNER_, _NEW_OWNER_);
_OWNER_ = _NEW_OWNER_;
_NEW_OWNER_ = address(0);
}
}
| contract InitializableOwnable {
address public _OWNER_;
address public _NEW_OWNER_;
bool internal _INITIALIZED_;
// ============ Events ============
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// ============ Modifiers ============
modifier notInitialized() {
require(!_INITIALIZED_, "mamacode_INITIALIZED");
_;
}
modifier onlyOwner() {
require(msg.sender == _OWNER_, "NOT_OWNER");
_;
}
// ============ Functions ============
function initOwner(address newOwner) public notInitialized {
_INITIALIZED_ = true;
_OWNER_ = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferPrepared(_OWNER_, newOwner);
_NEW_OWNER_ = newOwner;
}
function claimOwnership() public {
require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM");
emit OwnershipTransferred(_OWNER_, _NEW_OWNER_);
_OWNER_ = _NEW_OWNER_;
_NEW_OWNER_ = address(0);
}
}
| 25,767 |
5 | // Sets the address of the ISwap-compatible router _routerArray The addresses of routers _tokenArray The addresses of tokens that need to be approved by the strategy / | function setRouter(
address[] calldata _routerArray,
address[] calldata _tokenArray
)
external
| function setRouter(
address[] calldata _routerArray,
address[] calldata _tokenArray
)
external
| 3,317 |
94 | // If `account` had not been already granted `role`, emits a {RoleGranted}event. Requirements: - the caller must have ``role``'s admin role. / | function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
| function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
| 474 |
6 | // get requestId for call back | int256 chainId;
int256 groupId;
(chainId, groupId) = vrfCore.getChainIdAndGroupId();
requestId = makeRequestId(chainId, groupId, _keyHash, preSeed);
pendingRequests[requestId] = _vrfCoreAddress;
return requestId;
| int256 chainId;
int256 groupId;
(chainId, groupId) = vrfCore.getChainIdAndGroupId();
requestId = makeRequestId(chainId, groupId, _keyHash, preSeed);
pendingRequests[requestId] = _vrfCoreAddress;
return requestId;
| 34,992 |
6 | // Maximum value that can be converted to fixed point. Optimize for deployment.Test maxNewFixed() equals maxUint256() / fixed1() / | function maxNewFixed() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
| function maxNewFixed() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
| 22,697 |
151 | // We can directly increment and decrement the balances. | --_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
| --_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
| 1,571 |
0 | // Raises x to the power of n with scaling factor of base. x Base of the exponentiation n Exponent base Scaling factorreturn z Exponential of n with base x / | function pow(
uint256 x,
uint256 n,
uint256 base
| function pow(
uint256 x,
uint256 n,
uint256 base
| 6,919 |
7 | // Determine whether transfer was successful using status & result. | let success := and(
| let success := and(
| 22,708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.