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 |
|---|---|---|---|---|
92 | // Returns the number of members in the registry. / | function getNbMembers() external view returns (uint256) {
return _members.length;
}
| function getNbMembers() external view returns (uint256) {
return _members.length;
}
| 15,862 |
0 | // PROOF ASSET TOKEN (PRS)PRF TOKEN INFOPRS TOKEN MARKETINGPRS TOKEN MECHANICS / | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 27,660 |
2 | // Check the total underyling token balance to see if we should earn(); | function balance() public view returns (uint256) {
return
token.balanceOf(address(this)).add(
IStrategy(strategy).balanceOf()
);
}
| function balance() public view returns (uint256) {
return
token.balanceOf(address(this)).add(
IStrategy(strategy).balanceOf()
);
}
| 24,099 |
23 | // End 21 Dec 2017 11:00 EST => 21 Dec 2017 16:00 UTC => 21 Dec 2017 03:00 AEST new Date(15138720001000).toUTCString() => "Thu, 21 Dec 2017 16:00:00 UTC" | uint public endDate = 1517238822; // Mon 29 Jan 2018 15:13:42 UTC
| uint public endDate = 1517238822; // Mon 29 Jan 2018 15:13:42 UTC
| 10,536 |
132 | // Get LP token value of input amount of tokens | function stableToLp(uint256[N_COINS] calldata tokenAmounts, bool deposit) external view override returns (uint256) {
return _stableToLp(tokenAmounts, deposit);
}
| function stableToLp(uint256[N_COINS] calldata tokenAmounts, bool deposit) external view override returns (uint256) {
return _stableToLp(tokenAmounts, deposit);
}
| 35,249 |
10 | // The bit number where GameOption data starts | uint constant internal GAME_OPTIONS_BIT_OFFSET = 18;
| uint constant internal GAME_OPTIONS_BIT_OFFSET = 18;
| 2,233 |
20 | // make token name passed as exists | tokenNameExists[_name] = true;
| tokenNameExists[_name] = true;
| 10,432 |
6 | // buy |
if(from != owner() && to != owner() && pair[from]) {
require(balanceOf(to) + amount <= _maxWalletSize, "TOKEN: Amount exceeds maximum wallet size");
}
|
if(from != owner() && to != owner() && pair[from]) {
require(balanceOf(to) + amount <= _maxWalletSize, "TOKEN: Amount exceeds maximum wallet size");
}
| 17,852 |
9 | // the search value uses the same number of digits as the token | uint256 high = (uint256(fromAsset.liability()).wmul(endCovRatio) - fromAsset.cash()).fromWad(decimals);
uint256 low = 1;
| uint256 high = (uint256(fromAsset.liability()).wmul(endCovRatio) - fromAsset.cash()).fromWad(decimals);
uint256 low = 1;
| 30,212 |
47 | // Whether `a` is greater than `b`. a an int256. b a FixedPoint.Signed.return True if `a > b`, or False. / | function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
| function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
| 34,140 |
48 | // Global accounting state | uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
| uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
| 81,761 |
222 | // no price based percentage > date based percentage | vested = _beneficiaryAllocations[userAddress]
.amount
.mul(effectiveDaysVested)
.div(_duration);
| vested = _beneficiaryAllocations[userAddress]
.amount
.mul(effectiveDaysVested)
.div(_duration);
| 74,157 |
230 | // 可停止的合约 | contract Pausable is Ownable {
event Pause(); // 停止事件
event Unpause(); // 继续事件
bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
| contract Pausable is Ownable {
event Pause(); // 停止事件
event Unpause(); // 继续事件
bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
| 44,116 |
90 | // Mapping are cheaper than arrays | mapping(uint256 => Lottery) private _lotteries;
mapping(uint256 => Ticket) private _tickets;
| mapping(uint256 => Lottery) private _lotteries;
mapping(uint256 => Ticket) private _tickets;
| 33,926 |
10 | // hash link are out of sync | emit InvokeStatus(statusHashLinkOutOfSync);
return;
| emit InvokeStatus(statusHashLinkOutOfSync);
return;
| 14,865 |
83 | // Updates lastSalePrice if seller is the nft contract/ Otherwise, works the same as default bid method. | function bid(uint256 _tokenId)
public
payable
| function bid(uint256 _tokenId)
public
payable
| 2,262 |
41 | // solhint-disable func-name-mixedcase/ABI encode a standard, string revert error payload./This is the same payload that would be included by a `revert(string)`/solidity statement. It has the function signature `Error(string)`./message The error string./ return The ABI encoded error. | function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
| function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
| 36,937 |
30 | // transfer asset in | pool.asset.safeTransferFrom(_msgSender(), address(this), amount);
| pool.asset.safeTransferFrom(_msgSender(), address(this), amount);
| 40,333 |
62 | // gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei | uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei);
assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128...
return uint128(fullGasCostEthWei);
| uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei);
assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128...
return uint128(fullGasCostEthWei);
| 28,341 |
88 | // Now it is safe to delete _opPokeData. | delete _opPokeData;
| delete _opPokeData;
| 20,783 |
21 | // 如果有推荐人需分给推荐人 | if(winbill.referrer != address(0)) {
refRetrun = (allReturn * referrerRate) / 10000;
myfee = allReturn - netRetrun - refRetrun;
}
| if(winbill.referrer != address(0)) {
refRetrun = (allReturn * referrerRate) / 10000;
myfee = allReturn - netRetrun - refRetrun;
}
| 7,241 |
34 | // Enumerate valid NFTs/Throws if `_index` >= `totalSupply()`./_index A counter less than `totalSupply()`/ return The token identifier for the `_index`th NFT,/(sort order not specified) | function tokenByIndex(uint256 _index) external view returns (uint256);
| function tokenByIndex(uint256 _index) external view returns (uint256);
| 35,527 |
0 | // Emitted when the token is constructed | event ERC721ControlledInitialized(
string name,
string symbol
);
| event ERC721ControlledInitialized(
string name,
string symbol
);
| 13,173 |
70 | // Shifting right by 1 is like dividing by 2. | let half := shr(1, scalar)
for {
| let half := shr(1, scalar)
for {
| 5,493 |
13 | // REDUCE USER CLAIMABLE | totalClaimable[msg.sender] -= _claimCount;
| totalClaimable[msg.sender] -= _claimCount;
| 2,183 |
604 | // Executes multiple calls of fillOrder./orders Array of order specifications./takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders./signatures Proofs that orders have been created by makers./ return Array of amounts filled and fees paid by makers and taker. | function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
| function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
| 54,993 |
137 | // Trade freeze settings | function setPostTradeFreeze(uint256 _frozenForSeconds) public onlyTeamOrOwner {
freezePostTradeForSeconds = _frozenForSeconds;
}
| function setPostTradeFreeze(uint256 _frozenForSeconds) public onlyTeamOrOwner {
freezePostTradeForSeconds = _frozenForSeconds;
}
| 11,011 |
253 | // withdraw balance to owner of the smart contract / | function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
| function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
| 7,324 |
126 | // StakedAave StakedToken with AAVE token as staked token Aave / | contract StakedAave is StakedToken {
string internal constant NAME = 'Staked Aave';
string internal constant SYMBOL = 'stkAAVE';
uint8 internal constant DECIMALS = 18;
constructor(
IERC20 stakedToken,
IERC20 rewardToken,
uint256 cooldownSeconds,
uint256 unstakeWindow,
address rewardsVault,
address emissionManager,
uint128 distributionDuration
) public StakedToken(
stakedToken,
rewardToken,
cooldownSeconds,
unstakeWindow,
rewardsVault,
emissionManager,
distributionDuration,
NAME,
SYMBOL,
DECIMALS) {}
} | contract StakedAave is StakedToken {
string internal constant NAME = 'Staked Aave';
string internal constant SYMBOL = 'stkAAVE';
uint8 internal constant DECIMALS = 18;
constructor(
IERC20 stakedToken,
IERC20 rewardToken,
uint256 cooldownSeconds,
uint256 unstakeWindow,
address rewardsVault,
address emissionManager,
uint128 distributionDuration
) public StakedToken(
stakedToken,
rewardToken,
cooldownSeconds,
unstakeWindow,
rewardsVault,
emissionManager,
distributionDuration,
NAME,
SYMBOL,
DECIMALS) {}
} | 19,902 |
59 | // update _invite info | require(_invite != address(0) ,"invite cannot be null" );
user.invite = _invite;
referArr[_invite].push(msg.sender);
uint counterTmp = serialAddr[_invite];
if (serialUser[counterTmp].depoistTime == 0){
if (serialUser[counterTmp].withdrawPermissionCounts==0){
serialAddr[_invite]=counter;
counter = counter.add(1);
}
| require(_invite != address(0) ,"invite cannot be null" );
user.invite = _invite;
referArr[_invite].push(msg.sender);
uint counterTmp = serialAddr[_invite];
if (serialUser[counterTmp].depoistTime == 0){
if (serialUser[counterTmp].withdrawPermissionCounts==0){
serialAddr[_invite]=counter;
counter = counter.add(1);
}
| 9,696 |
3 | // Delegates request of finishing to the Voting base contract/ | function finish() public {
VotingLib.delegatecallFinish(baseVoting);
}
| function finish() public {
VotingLib.delegatecallFinish(baseVoting);
}
| 9,211 |
26 | // =================== OVERRIDES =================== / | function mintTo(address, uint256) public pure override {
require(false, "Use mint function instead");
}
| function mintTo(address, uint256) public pure override {
require(false, "Use mint function instead");
}
| 42,458 |
2 | // public variables | mapping(uint256 => mapping(address => bool)) public Proj_to_voted; // mapping var. to check whether a user voted for the project(proposal)
address public Owner; // owner of the contract
mapping(uint256 => Project) public Projects; // project id -> project
mapping(address => uint256) public Proposed; // counting how many projects/proposals were suggested by a user
uint256 public Project_num; // variable to track the number of proposals suggested (from all users)
uint256 public Proposal_limit; // per-person limit for suggesting new proposals
| mapping(uint256 => mapping(address => bool)) public Proj_to_voted; // mapping var. to check whether a user voted for the project(proposal)
address public Owner; // owner of the contract
mapping(uint256 => Project) public Projects; // project id -> project
mapping(address => uint256) public Proposed; // counting how many projects/proposals were suggested by a user
uint256 public Project_num; // variable to track the number of proposals suggested (from all users)
uint256 public Proposal_limit; // per-person limit for suggesting new proposals
| 6,926 |
161 | // do unstaking, first-in last-out, respecting time bonus | uint256 timeWeightedShareSeconds = _unstakeFirstInLastOut(amount);
| uint256 timeWeightedShareSeconds = _unstakeFirstInLastOut(amount);
| 34,154 |
14 | // If the contract holds no tokens at all, don't proceed. | if (poolBalance == 0) {
pool.lastRewardBlock = block.number;
return;
}
| if (poolBalance == 0) {
pool.lastRewardBlock = block.number;
return;
}
| 24,134 |
195 | // no need for unstaking/rewards computation | if (amount == 0) {
return (0, 0, 0, totalUnlocked().add(deltaUnlocked));
}
| if (amount == 0) {
return (0, 0, 0, totalUnlocked().add(deltaUnlocked));
}
| 38,152 |
401 | // Issuer of the document. SSTORAGE 1 full after this. | address issuer;
| address issuer;
| 15,043 |
145 | // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. | unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (!ownership.burned) {
if (tokenIdsIdx == index) {
return i;
}
| unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (!ownership.burned) {
if (tokenIdsIdx == index) {
return i;
}
| 9,498 |
10 | // The total number of tokens released in the lifetime of the TokenCapacitor | uint256 public lifetimeReleasedTokens;
| uint256 public lifetimeReleasedTokens;
| 16,194 |
86 | // 获取记录 | function getRef(address _user) public view returns (address[] memory ){
return referArr[_user];
}
| function getRef(address _user) public view returns (address[] memory ){
return referArr[_user];
}
| 61,417 |
13 | // 3 bytes for each pixel | uint8 byteIndex = offset + pixelIndex * 3;
| uint8 byteIndex = offset + pixelIndex * 3;
| 15,737 |
1 | // Given All initial tokens to admin | balanceOf[msg.sender] = _initalSupply;
totalSupply = _initalSupply;
| balanceOf[msg.sender] = _initalSupply;
totalSupply = _initalSupply;
| 29,006 |
31 | // Kyber constants contract | contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
| contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
| 7,940 |
234 | // Starts poll | uint pollID = voting.startPoll(
parameterizer.get("voteQuorum"),
parameterizer.get("commitStageLen"),
parameterizer.get("revealStageLen")
);
uint oneHundred = 100; // Kludge that we need to use SafeMath
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: ((oneHundred.sub(parameterizer.get("dispensationPct"))).mul(minDeposit)).div(100),
| uint pollID = voting.startPoll(
parameterizer.get("voteQuorum"),
parameterizer.get("commitStageLen"),
parameterizer.get("revealStageLen")
);
uint oneHundred = 100; // Kludge that we need to use SafeMath
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: ((oneHundred.sub(parameterizer.get("dispensationPct"))).mul(minDeposit)).div(100),
| 41,202 |
98 | // Checks if amount is within allowed burn bounds anddestroys `amount` tokens from `account`, reducing thetotal supply. account account to burn tokens for amount amount of tokens to burn | * Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
| * Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
| 18,576 |
73 | // Set the Max transaction amount (percent of total supply) | function set_Max_Transaction_Percent(uint256 maxTxPercent_x100) external onlyOwner() {
_maxTxAmount = _tTotal*maxTxPercent_x100/10000;
}
| function set_Max_Transaction_Percent(uint256 maxTxPercent_x100) external onlyOwner() {
_maxTxAmount = _tTotal*maxTxPercent_x100/10000;
}
| 18,588 |
154 | // Return an empty array | return new uint256[](0);
| return new uint256[](0);
| 5,658 |
15 | // A checkpoint for marking number of votes from a given block | struct Checkpoint {
uint32 fromBlock;
uint votes;
}
| struct Checkpoint {
uint32 fromBlock;
uint votes;
}
| 28,298 |
207 | // rabbit earn 10000 $CARROTZ per day | uint256 public constant DAILY_CARROTZ_RATE = 50 ether;
| uint256 public constant DAILY_CARROTZ_RATE = 50 ether;
| 7,479 |
43 | // Data types / | struct Staker {
uint deposit; // total amount of deposit sote
uint reward; // total amount that is ready to be claimed
address[] contracts; // list of contracts the staker has staked on
// staked amounts for each contract
mapping(address => uint) stakes;
// amount pending to be subtracted after all unstake requests will be processed
mapping(address => uint) pendingUnstakeRequestsTotal;
// flag to indicate the presence of this staker in the array of stakers of each contract
mapping(address => bool) isInContractStakers;
}
| struct Staker {
uint deposit; // total amount of deposit sote
uint reward; // total amount that is ready to be claimed
address[] contracts; // list of contracts the staker has staked on
// staked amounts for each contract
mapping(address => uint) stakes;
// amount pending to be subtracted after all unstake requests will be processed
mapping(address => uint) pendingUnstakeRequestsTotal;
// flag to indicate the presence of this staker in the array of stakers of each contract
mapping(address => bool) isInContractStakers;
}
| 1,003 |
256 | // Return remainder if exist | uint256 refundAmount = msg.value.sub(amount);
| uint256 refundAmount = msg.value.sub(amount);
| 10,604 |
30 | // See {IERC1155Receiver-onERC1155BatchReceived}. / | function onERC1155BatchReceived(
address,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external override nonReentrant returns (bytes4) {
require(
ids.length == 1 && ids.length == values.length,
"Invalid input"
| function onERC1155BatchReceived(
address,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external override nonReentrant returns (bytes4) {
require(
ids.length == 1 && ids.length == values.length,
"Invalid input"
| 16,441 |
360 | // Update the data in storage | if (withdrawBlock.withdrawals.length >= 32) {
assembly {
mstore(add(slice, offset), data)
}
| if (withdrawBlock.withdrawals.length >= 32) {
assembly {
mstore(add(slice, offset), data)
}
| 26,488 |
10 | // Set the FRAX address | FRAX = IFrax(_fraxErc20);
| FRAX = IFrax(_fraxErc20);
| 35,390 |
1 | // Faucet Time locked mini vault ERC20 Cyril Lapinte - <cyril@openfiz.com>SPDX-License-Identifier: MIT Error messages / | contract FaucetMock is Faucet {
function defineWithdrawStatusLastAtTest(
IERC20 _token,
address _beneficiary,
uint64 _lastAt) public returns (bool)
{
withdrawStatus_[_token][_beneficiary].lastAt = _lastAt;
return true;
}
}
| contract FaucetMock is Faucet {
function defineWithdrawStatusLastAtTest(
IERC20 _token,
address _beneficiary,
uint64 _lastAt) public returns (bool)
{
withdrawStatus_[_token][_beneficiary].lastAt = _lastAt;
return true;
}
}
| 9,906 |
78 | // RelayerModule Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer.Julien Niset - <julien@argent.im> / | contract RelayerModule is Module {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) public relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash);
/**
* @dev Throws if the call did not go through the execute() method.
*/
modifier onlyExecute {
require(msg.sender == address(this), "RM: must be called via execute()");
_;
}
/* ***************** Abstract method ************************* */
/**
* @dev Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures.
*/
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256);
/**
* @dev Validates the signatures provided with a relayed transaction.
* The method MUST throw if one or more signatures are not valid.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated byte array.
*/
function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool);
/* ************************************************************ */
/**
* @dev Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function execute(
BaseWallet _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit
)
external
returns (bool success)
{
uint startGas = gasleft();
bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit);
require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request");
require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data");
uint256 requiredSignatures = getRequiredSignatures(_wallet, _data);
if((requiredSignatures * 65) == _signatures.length) {
if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) {
if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) {
// solium-disable-next-line security/no-call-value
(success,) = address(this).call(_data);
refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender);
}
}
}
emit TransactionExecuted(address(_wallet), success, signHash);
}
/**
* @dev Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) {
return relayer[address(_wallet)].nonce;
}
/**
* @dev Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the module)
* @param _to The destination address for the relayed transaction (should be the wallet)
* @param _value The value for the relayed transaction
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function getSignHash(
address _from,
address _to,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit))
));
}
/**
* @dev Checks if the relayed transaction is unique.
* @param _wallet The target wallet.
* @param _nonce The nonce
* @param _signHash The signed hash of the transaction
*/
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) {
if(relayer[address(_wallet)].executedTx[_signHash] == true) {
return false;
}
relayer[address(_wallet)].executedTx[_signHash] = true;
return true;
}
/**
* @dev Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes.
* @param _wallet The target wallet.
* @param _nonce The nonce
*/
function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) {
if(_nonce <= relayer[address(_wallet)].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if(nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[address(_wallet)].nonce = _nonce;
return true;
}
/**
* @dev Recovers the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28);
return ecrecover(_signedHash, v, r, s);
}
/**
* @dev Refunds the gas used to the Relayer.
* For security reasons the default behavior is to not refund calls with 0 or 1 signatures.
* @param _wallet The target wallet.
* @param _gasUsed The gas used.
* @param _gasPrice The gas price for the refund.
* @param _gasLimit The gas limit for the refund.
* @param _signatures The number of signatures used in the call.
* @param _relayer The address of the Relayer.
*/
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed
// only refund if gas price not null, more than 1 signatures, gas less than gasLimit
if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) {
if(_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
}
else {
amount = amount * _gasPrice;
}
_wallet.invoke(_relayer, amount, "");
}
}
/**
* @dev Returns false if the refund is expected to fail.
* @param _wallet The target wallet.
* @param _gasUsed The expected gas used.
* @param _gasPrice The expected gas price for the refund.
*/
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if(_gasPrice > 0
&& _signatures > 1
&& (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) {
return false;
}
return true;
}
/**
* @dev Checks that the wallet address provided as the first parameter of the relayed data is the same
* as the wallet passed as the input of the execute() method.
@return false if the addresses are different.
*/
function verifyData(address _wallet, bytes memory _data) private pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
//_data = {length:32}{sig:4}{_wallet:32}{...}
dataWallet := mload(add(_data, 0x24))
}
return dataWallet == _wallet;
}
/**
* @dev Parses the data to extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "RM: Invalid functionPrefix");
// solium-disable-next-line security/no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
}
| contract RelayerModule is Module {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) public relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash);
/**
* @dev Throws if the call did not go through the execute() method.
*/
modifier onlyExecute {
require(msg.sender == address(this), "RM: must be called via execute()");
_;
}
/* ***************** Abstract method ************************* */
/**
* @dev Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures.
*/
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256);
/**
* @dev Validates the signatures provided with a relayed transaction.
* The method MUST throw if one or more signatures are not valid.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated byte array.
*/
function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool);
/* ************************************************************ */
/**
* @dev Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function execute(
BaseWallet _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit
)
external
returns (bool success)
{
uint startGas = gasleft();
bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit);
require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request");
require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data");
uint256 requiredSignatures = getRequiredSignatures(_wallet, _data);
if((requiredSignatures * 65) == _signatures.length) {
if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) {
if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) {
// solium-disable-next-line security/no-call-value
(success,) = address(this).call(_data);
refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender);
}
}
}
emit TransactionExecuted(address(_wallet), success, signHash);
}
/**
* @dev Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) {
return relayer[address(_wallet)].nonce;
}
/**
* @dev Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the module)
* @param _to The destination address for the relayed transaction (should be the wallet)
* @param _value The value for the relayed transaction
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function getSignHash(
address _from,
address _to,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit))
));
}
/**
* @dev Checks if the relayed transaction is unique.
* @param _wallet The target wallet.
* @param _nonce The nonce
* @param _signHash The signed hash of the transaction
*/
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) {
if(relayer[address(_wallet)].executedTx[_signHash] == true) {
return false;
}
relayer[address(_wallet)].executedTx[_signHash] = true;
return true;
}
/**
* @dev Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes.
* @param _wallet The target wallet.
* @param _nonce The nonce
*/
function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) {
if(_nonce <= relayer[address(_wallet)].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if(nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[address(_wallet)].nonce = _nonce;
return true;
}
/**
* @dev Recovers the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28);
return ecrecover(_signedHash, v, r, s);
}
/**
* @dev Refunds the gas used to the Relayer.
* For security reasons the default behavior is to not refund calls with 0 or 1 signatures.
* @param _wallet The target wallet.
* @param _gasUsed The gas used.
* @param _gasPrice The gas price for the refund.
* @param _gasLimit The gas limit for the refund.
* @param _signatures The number of signatures used in the call.
* @param _relayer The address of the Relayer.
*/
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed
// only refund if gas price not null, more than 1 signatures, gas less than gasLimit
if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) {
if(_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
}
else {
amount = amount * _gasPrice;
}
_wallet.invoke(_relayer, amount, "");
}
}
/**
* @dev Returns false if the refund is expected to fail.
* @param _wallet The target wallet.
* @param _gasUsed The expected gas used.
* @param _gasPrice The expected gas price for the refund.
*/
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if(_gasPrice > 0
&& _signatures > 1
&& (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) {
return false;
}
return true;
}
/**
* @dev Checks that the wallet address provided as the first parameter of the relayed data is the same
* as the wallet passed as the input of the execute() method.
@return false if the addresses are different.
*/
function verifyData(address _wallet, bytes memory _data) private pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
//_data = {length:32}{sig:4}{_wallet:32}{...}
dataWallet := mload(add(_data, 0x24))
}
return dataWallet == _wallet;
}
/**
* @dev Parses the data to extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "RM: Invalid functionPrefix");
// solium-disable-next-line security/no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
}
| 35,285 |
3 | // Throws if the sender is not a listed adapter / | modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
| modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
| 38,998 |
28 | // - sets the value `true` for {PersonalInfo.hasOwnSecondaryLimit}/- sets the value `_newLimit` for {PersonalInfo.individualSecondaryTradingLimit} | function _setSecondaryTradingLimitFor(
address _account,
uint256 _newLimit
) internal {
userData[_account].hasOwnSecondaryLimit = true;
userData[_account].individualSecondaryTradingLimit = _newLimit;
}
| function _setSecondaryTradingLimitFor(
address _account,
uint256 _newLimit
) internal {
userData[_account].hasOwnSecondaryLimit = true;
userData[_account].individualSecondaryTradingLimit = _newLimit;
}
| 24,106 |
22 | // allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errors also, to minimize the risk of the approve/transferFrom attack vector in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value_spender approved address_value allowance amount return true if the approval was successful, false if it wasn't/ | function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
| function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
| 54,260 |
31 | // Return the account balance of some account/_tokenHolder Address for which the balance is returned/ return the balance of `_tokenAddress`. | function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; }
| function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; }
| 19,146 |
5 | // Minimal interface for CryptoDevsNFT containing only two functionsthat we are interested in / | interface ICryptoDevsNFT {
/// @dev balanceOf returns the number of NFTs owned by the given address
/// @param owner - address to fetch number of NFTs for
/// @return Returns the number of NFTs owned
function balanceOf(address owner) external view returns (uint256);
/// @dev tokenOfOwnerByIndex returns a tokenID at given index for owner
/// @param owner - address to fetch the NFT TokenID for
/// @param index - index of NFT in owned tokens array to fetch
/// @return Returns the TokenID of the NFT
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256);
}
| interface ICryptoDevsNFT {
/// @dev balanceOf returns the number of NFTs owned by the given address
/// @param owner - address to fetch number of NFTs for
/// @return Returns the number of NFTs owned
function balanceOf(address owner) external view returns (uint256);
/// @dev tokenOfOwnerByIndex returns a tokenID at given index for owner
/// @param owner - address to fetch the NFT TokenID for
/// @param index - index of NFT in owned tokens array to fetch
/// @return Returns the TokenID of the NFT
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256);
}
| 50,888 |
25 | // get state | function maxReserve() external view returns(uint);
function calcUpdateNAV() external returns (uint);
function seniorDebt() external returns(uint);
function seniorBalance() external returns(uint);
function seniorRatioBounds() external view returns(Fixed27 memory minSeniorRatio, Fixed27 memory maxSeniorRatio);
function totalBalance() external returns(uint);
| function maxReserve() external view returns(uint);
function calcUpdateNAV() external returns (uint);
function seniorDebt() external returns(uint);
function seniorBalance() external returns(uint);
function seniorRatioBounds() external view returns(Fixed27 memory minSeniorRatio, Fixed27 memory maxSeniorRatio);
function totalBalance() external returns(uint);
| 8,780 |
222 | // Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals )msg.sender will be the _payer only the _payer can make additionals if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used_requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data _payeesPaymentAddress array of payees address for payment (optional)_payeeAmounts array of amount repartition for the payment _additionals array to increase the ExpectedAmount for payees _expirationDate timestamp after that the signed request cannot be broadcasted _signature ECDSA signature in bytes return Returns the id of the request / | function broadcastSignedRequestAsPayerAction(
bytes _requestData, // gather data to avoid "stack too deep"
address[] _payeesPaymentAddress,
uint256[] _payeeAmounts,
uint256[] _additionals,
uint256 _expirationDate,
bytes _signature)
external
payable
whenNotPaused
| function broadcastSignedRequestAsPayerAction(
bytes _requestData, // gather data to avoid "stack too deep"
address[] _payeesPaymentAddress,
uint256[] _payeeAmounts,
uint256[] _additionals,
uint256 _expirationDate,
bytes _signature)
external
payable
whenNotPaused
| 68,742 |
39 | // Don't allow blacklisted wallets to receive or send tokens. | require(!fromWalletState.isBlacklisted && !toWalletState.isBlacklisted, "blacklisted");
uint256 fees = 0;
bool takeFee = !fromWalletState.isExcludedFromFees && !toWalletState.isExcludedFromFees;
| require(!fromWalletState.isBlacklisted && !toWalletState.isBlacklisted, "blacklisted");
uint256 fees = 0;
bool takeFee = !fromWalletState.isExcludedFromFees && !toWalletState.isExcludedFromFees;
| 10,685 |
126 | // send reward | _reward = (_profits * issueDividendRewardBips) / 10000;
_sendReward(_reward);
| _reward = (_profits * issueDividendRewardBips) / 10000;
_sendReward(_reward);
| 20,765 |
156 | // the below function calculates where tokens needs to go based on the inputted amount of tokens. n.b., this function does not work in reflections, those typically happen later in the processing when the token distribution calculated by this function is turned to reflections based on the golden ratio of total token supply to total reflections. | function _getTokenValues(uint256 amountOfTokens)
private
view
returns (
uint256,
uint256,
uint256
)
| function _getTokenValues(uint256 amountOfTokens)
private
view
returns (
uint256,
uint256,
uint256
)
| 10,845 |
15 | // Gas amount used to execute this funded function | uint256 gasAmountForExecution; // [gas amount]
| uint256 gasAmountForExecution; // [gas amount]
| 2,007 |
140 | // Internal function for validating version of the received message _messageId id of the received message / | function _isMessageVersionValid(bytes32 _messageId) internal returns (bool) {
return
_messageId & 0xffffffff00000000000000000000000000000000000000000000000000000000 == MESSAGE_PACKING_VERSION;
}
| function _isMessageVersionValid(bytes32 _messageId) internal returns (bool) {
return
_messageId & 0xffffffff00000000000000000000000000000000000000000000000000000000 == MESSAGE_PACKING_VERSION;
}
| 7,707 |
79 | // Approve the passed address to spend the specified amount of tokens on behalf ofmsg.sender. This method is included for ERC20 compatibility.increaseAllowance and decreaseAllowance should be used instead.Changing an allowance with this method brings the risk that someone may transfer boththe old and the new allowance - if they are both greater than zero - if a transfertransaction is mined before the later approve() call is mined.spender The address which will spend the funds. value The amount of tokens to be spent. / |
function approve(address spender, uint256 value)
public
returns (bool)
|
function approve(address spender, uint256 value)
public
returns (bool)
| 38,600 |
54 | // locked | locked[_participant] = true;
| locked[_participant] = true;
| 49,072 |
489 | // gets all interfaces of given instance | function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
| function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
| 27,971 |
78 | // address list: address _uniswapV2Factory, address _uniswapV2Router02, address _askoStaking, address _lotteryFactory, | address[4] memory addressData,
address payable _admin,
string memory _tokenName,
string memory _tokenSymbol,
uint256 _tokenPrice,
uint256 _tokenMaxSupply,
uint256 _ETHMaxSupply,
uint256 _uniswapTokenSupplyPercentNumerator,
uint256 _stakersETHRewardsPercentNumerator,
uint256 _adminFeesETHPercentNumerator,
| address[4] memory addressData,
address payable _admin,
string memory _tokenName,
string memory _tokenSymbol,
uint256 _tokenPrice,
uint256 _tokenMaxSupply,
uint256 _ETHMaxSupply,
uint256 _uniswapTokenSupplyPercentNumerator,
uint256 _stakersETHRewardsPercentNumerator,
uint256 _adminFeesETHPercentNumerator,
| 54,089 |
14 | // -从[msg.sender]转移[amount]枚[命运神殿令牌]至[to]. [允许任何人调用] -[msg.sender]需要有足够的余额.to -接收地址.amount -数量. / | function transfer(address to, uint256 amount) external verifyBalance(_balances[msg.sender],amount) returns (bool) {
unchecked{
_balances[msg.sender] -= amount;
_balances[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
| function transfer(address to, uint256 amount) external verifyBalance(_balances[msg.sender],amount) returns (bool) {
unchecked{
_balances[msg.sender] -= amount;
_balances[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
| 33,834 |
26 | // Validates the initial registry of a legal entity or the change of its registryaddr Ethereum address that needs to be validatedidProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account.This PDF is signed with eCNPJ and send to BNDES. / | function validateRegistryLegalEntity(address addr, string memory idProofHash) public {
require(isResponsibleForRegistryValidation(msg.sender), "Somente o responsável pela validação pode validar contas");
require(legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION, "A conta precisa estar no estado Aguardando Validação");
require(keccak256(abi.encodePacked(legalEntitiesInfo[addr].idProofHash)) == keccak256(abi.encodePacked(idProofHash)), "O hash recebido é diferente do esperado");
legalEntitiesInfo[addr].state = BlockchainAccountState.VALIDATED;
emit AccountValidation(addr, legalEntitiesInfo[addr].cnpj,
legalEntitiesInfo[addr].idFinancialSupportAgreement,
legalEntitiesInfo[addr].salic);
}
| function validateRegistryLegalEntity(address addr, string memory idProofHash) public {
require(isResponsibleForRegistryValidation(msg.sender), "Somente o responsável pela validação pode validar contas");
require(legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION, "A conta precisa estar no estado Aguardando Validação");
require(keccak256(abi.encodePacked(legalEntitiesInfo[addr].idProofHash)) == keccak256(abi.encodePacked(idProofHash)), "O hash recebido é diferente do esperado");
legalEntitiesInfo[addr].state = BlockchainAccountState.VALIDATED;
emit AccountValidation(addr, legalEntitiesInfo[addr].cnpj,
legalEntitiesInfo[addr].idFinancialSupportAgreement,
legalEntitiesInfo[addr].salic);
}
| 28,122 |
65 | // CollectionAddressRemoved Emitted when a cloned collection contract address is removed. | event CollectionAddressRemoved(address indexed implementationAddress, address indexed collectionAddress);
| event CollectionAddressRemoved(address indexed implementationAddress, address indexed collectionAddress);
| 11,779 |
10 | // Zap In - Step 2 (optional) Requires user to run: DelegateApprovals.approveExchangeOnBehalf(<zap_contract_address>) synthetix DelegateApprovals contract: 0x15fd6e554874B9e70F832Ed37f231Ac5E142362f | function swapEthToSeth() external payable {
uint256 swappingEthAmount = address(this).balance;
swapRouter.swapExactETHForTokens{value: swappingEthAmount}(swappingEthAmount, swapPathZapIn, address(this), now);
uint256 susdAmount = sUsd.balanceOf(address(this));
sUsd.transfer(msg.sender, susdAmount);
synthetix.exchangeOnBehalf(msg.sender, "sUSD", susdAmount, "sETH");
}
| function swapEthToSeth() external payable {
uint256 swappingEthAmount = address(this).balance;
swapRouter.swapExactETHForTokens{value: swappingEthAmount}(swappingEthAmount, swapPathZapIn, address(this), now);
uint256 susdAmount = sUsd.balanceOf(address(this));
sUsd.transfer(msg.sender, susdAmount);
synthetix.exchangeOnBehalf(msg.sender, "sUSD", susdAmount, "sETH");
}
| 39,345 |
8 | // 2. Performing the actions |
ended = true;
emit AuctionEnded (highestBidder, highestBid);
|
ended = true;
emit AuctionEnded (highestBidder, highestBid);
| 7,020 |
35 | // clear tax | bool success = _collectTax(tokenId_);
| bool success = _collectTax(tokenId_);
| 33,360 |
345 | // Scaling factor for entering positions as the fcash estimations have rounding errors | uint256 internal constant FCASH_SCALING = 9_995;
| uint256 internal constant FCASH_SCALING = 9_995;
| 2,268 |
132 | // Function to get all stakeholder addresses who have contributed at least 5 ETH | function getStakeholdersWithMinimumContribution() external view returns (address[] memory) {
address[] memory result = new address[](stakeHolders.length);
uint256 count = 0;
for (uint256 i = 0; i < stakeHolders.length; i++) {
if (contributors[stakeHolders[i]] >= 5 ether) {
result[count] = stakeHolders[i];
count++;
}
}
// Resize the result array to eliminate any empty slots
assembly {
mstore(result, count)
}
return result;
}
| function getStakeholdersWithMinimumContribution() external view returns (address[] memory) {
address[] memory result = new address[](stakeHolders.length);
uint256 count = 0;
for (uint256 i = 0; i < stakeHolders.length; i++) {
if (contributors[stakeHolders[i]] >= 5 ether) {
result[count] = stakeHolders[i];
count++;
}
}
// Resize the result array to eliminate any empty slots
assembly {
mstore(result, count)
}
return result;
}
| 23,824 |
44 | // main functions | function updateAirlineFeePayed(address _airlineAddress, bool payed) external returns (bool);
function registerAirline(address _existingAirline, string _id, string _name, address _airlineAddress, bool isRegistered, bool registrationFeePayed) external;
function fetchAirline(address airlineAddress) external view returns (string id, string name, bool isRegistered, bool registrationFeePayed);
function fetchRegisteredAirlines() external view returns (uint numOfAirlines);
function fetchAllAirlines() external view returns (address[]);
| function updateAirlineFeePayed(address _airlineAddress, bool payed) external returns (bool);
function registerAirline(address _existingAirline, string _id, string _name, address _airlineAddress, bool isRegistered, bool registrationFeePayed) external;
function fetchAirline(address airlineAddress) external view returns (string id, string name, bool isRegistered, bool registrationFeePayed);
function fetchRegisteredAirlines() external view returns (uint numOfAirlines);
function fetchAllAirlines() external view returns (address[]);
| 31,067 |
76 | // Calculate each order's fill amount. | function calculateRingFillAmount(
uint ringSize,
OrderState[] orders
)
private
pure
| function calculateRingFillAmount(
uint ringSize,
OrderState[] orders
)
private
pure
| 42,315 |
35 | // | * @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
| * @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
| 9,465 |
3 | // Emitted when an admin removes a market | event MarketRemoved(CToken cToken);
| event MarketRemoved(CToken cToken);
| 22,319 |
42 | // Set the spender's token allowance to tokenQty | require(ERC20Token(_token).approve(address(kyberNetworkProxy), _amount), "Failed to approve trade amount");
(ratePer1Token,) = kyberNetworkProxy.getExpectedRate(_token, SNT, 1 ether);
(tokensToTradeRate,) = kyberNetworkProxy.getExpectedRate(_token, SNT, _amount);
minAcceptedRate = (ratePer1Token * (10000 - maxSlippageRate)) / 10000;
require(tokensToTradeRate >= minAcceptedRate, "Rate is not acceptable");
destAmount = kyberNetworkProxy.trade(_token, _amount, SNT, burnAddress, 0 - uint256(1), tokensToTradeRate, walletId);
emit Swap(msg.sender, _token, SNT, _amount, destAmount);
| require(ERC20Token(_token).approve(address(kyberNetworkProxy), _amount), "Failed to approve trade amount");
(ratePer1Token,) = kyberNetworkProxy.getExpectedRate(_token, SNT, 1 ether);
(tokensToTradeRate,) = kyberNetworkProxy.getExpectedRate(_token, SNT, _amount);
minAcceptedRate = (ratePer1Token * (10000 - maxSlippageRate)) / 10000;
require(tokensToTradeRate >= minAcceptedRate, "Rate is not acceptable");
destAmount = kyberNetworkProxy.trade(_token, _amount, SNT, burnAddress, 0 - uint256(1), tokensToTradeRate, walletId);
emit Swap(msg.sender, _token, SNT, _amount, destAmount);
| 13,221 |
45 | // In-between chars must between 'a' and 'z' or '-'. Otherwise, they should be the unset bytes. The last part is verifiied by requiring that an in-bewteen char that is NULL must also be follwed by a NULL. | if ( !(_isLowercaseLetter(_id[i]) || (_id[i] == 0x2D && _id[i+1] != 0) || (_id[i] == _id[i+1] && _id[i] == 0)) )
{
return false;
}
| if ( !(_isLowercaseLetter(_id[i]) || (_id[i] == 0x2D && _id[i+1] != 0) || (_id[i] == _id[i+1] && _id[i] == 0)) )
{
return false;
}
| 23,435 |
215 | // Used to change a fee taker newAddress New fee taker address. / | function setFeeTaker(address payable newAddress) public _ownerOnly {
feeTaker = newAddress;
}
| function setFeeTaker(address payable newAddress) public _ownerOnly {
feeTaker = newAddress;
}
| 10,902 |
298 | // Put a EtherDog up for auction to be sire./Performs checks to ensure the EtherDog can be sired, then/delegates to reverse auction. | function createSiringAuction(
uint256 _EtherDogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
| function createSiringAuction(
uint256 _EtherDogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
| 20,933 |
17 | // Function for changing the total amount of activated validators.newActivatedValidators - new total amount of activated validators./ | function setActivatedValidators(uint256 newActivatedValidators) external;
| function setActivatedValidators(uint256 newActivatedValidators) external;
| 31,786 |
92 | // Internal function to transfer debt and collateral from Yield to MakerDAO | /// Needs vat.hope(splitter.address, { from: user });
/// Needs controller.addDelegate(splitter.address, { from: user });
/// @param pool The pool to trade in (and therefore fyDai series to migrate)
/// @param user Vault to migrate.
/// @param wethAmount weth to move from Yield to MakerDAO. Needs to be high enough to collateralize the dai debt in MakerDAO,
/// and low enough to make sure that debt left in Yield is also collateralized.
/// @param fyDaiAmount fyDai debt to move from Yield to MakerDAO.
/// @param maxFYDaiPrice Maximum Dai price to pay for fyDai.
function _exportPosition(IPool pool, address user, uint256 wethAmount, uint256 fyDaiAmount, uint256 maxFYDaiPrice) internal {
// We are going to need to buy the FYDai back with Dai borrowed from Maker
uint256 daiAmount = pool.buyFYDaiPreview(fyDaiAmount.toUint128());
require(
daiAmount <= muld(fyDaiAmount, maxFYDaiPrice),
"ExportProxy: Maximum fyDai price exceeded"
);
IFYDai fyDai = IFYDai(pool.fyDai());
// Pay the Yield debt - ExportProxy pays FYDai to remove the debt of `user`
// Controller should take exactly all fyDai flash minted.
controller.repayFYDai(WETH, fyDai.maturity(), address(this), user, fyDaiAmount);
// Withdraw the collateral from Yield, ExportProxy will hold it
controller.withdraw(WETH, user, address(this), wethAmount);
// Post the collateral to Maker, in the `user` vault
wethJoin.join(user, wethAmount);
// Borrow the Dai from Maker
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee for Weth
vat.frob(
"ETH-A",
user,
user,
user,
wethAmount.toInt256(), // Adding Weth collateral
divdrup(daiAmount, rate).toInt256() // Adding Dai debt
);
vat.move(user, address(this), daiAmount.mul(UNIT)); // Transfer the Dai to ExportProxy within MakerDAO, in RAD
daiJoin.exit(address(this), daiAmount); // ExportProxy will hold the dai temporarily
// Sell the Dai for FYDai at Pool - It should make up for what was taken with repayYdai
pool.buyFYDai(address(this), address(this), fyDaiAmount.toUint128());
}
| /// Needs vat.hope(splitter.address, { from: user });
/// Needs controller.addDelegate(splitter.address, { from: user });
/// @param pool The pool to trade in (and therefore fyDai series to migrate)
/// @param user Vault to migrate.
/// @param wethAmount weth to move from Yield to MakerDAO. Needs to be high enough to collateralize the dai debt in MakerDAO,
/// and low enough to make sure that debt left in Yield is also collateralized.
/// @param fyDaiAmount fyDai debt to move from Yield to MakerDAO.
/// @param maxFYDaiPrice Maximum Dai price to pay for fyDai.
function _exportPosition(IPool pool, address user, uint256 wethAmount, uint256 fyDaiAmount, uint256 maxFYDaiPrice) internal {
// We are going to need to buy the FYDai back with Dai borrowed from Maker
uint256 daiAmount = pool.buyFYDaiPreview(fyDaiAmount.toUint128());
require(
daiAmount <= muld(fyDaiAmount, maxFYDaiPrice),
"ExportProxy: Maximum fyDai price exceeded"
);
IFYDai fyDai = IFYDai(pool.fyDai());
// Pay the Yield debt - ExportProxy pays FYDai to remove the debt of `user`
// Controller should take exactly all fyDai flash minted.
controller.repayFYDai(WETH, fyDai.maturity(), address(this), user, fyDaiAmount);
// Withdraw the collateral from Yield, ExportProxy will hold it
controller.withdraw(WETH, user, address(this), wethAmount);
// Post the collateral to Maker, in the `user` vault
wethJoin.join(user, wethAmount);
// Borrow the Dai from Maker
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee for Weth
vat.frob(
"ETH-A",
user,
user,
user,
wethAmount.toInt256(), // Adding Weth collateral
divdrup(daiAmount, rate).toInt256() // Adding Dai debt
);
vat.move(user, address(this), daiAmount.mul(UNIT)); // Transfer the Dai to ExportProxy within MakerDAO, in RAD
daiJoin.exit(address(this), daiAmount); // ExportProxy will hold the dai temporarily
// Sell the Dai for FYDai at Pool - It should make up for what was taken with repayYdai
pool.buyFYDai(address(this), address(this), fyDaiAmount.toUint128());
}
| 33,844 |
99 | // revert if sender is whiteListAgent | modifier OnlyWhiteListAgent() {
require(msg.sender == whiteListAgent);
_;
}
| modifier OnlyWhiteListAgent() {
require(msg.sender == whiteListAgent);
_;
}
| 48,919 |
10 | // Operational functions ------------------------------------------------------------------------ | function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
artistRoyalty = 0;
ownerRoyalty = 0;
emit Withdraw(msg.sender, balance);
}
| function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
artistRoyalty = 0;
ownerRoyalty = 0;
emit Withdraw(msg.sender, balance);
}
| 22,857 |
2 | // computes a reduced-scalar ratio_n ratio numerator _d ratio denominator _max maximum desired scalar return ratio's numerator and denominator / | function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
| function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
| 14,311 |
0 | // You can update the msg.sender address with your front-end address to mint yourself tokens._mint(0x697D940BC9A2aa8F56c1eC65E640951781C98A23, 1000 ether); This mints to the deployer | _mint(msg.sender, 1000 ether);
| _mint(msg.sender, 1000 ether);
| 46,172 |
10 | // Emitted when a sell order is removed, either by being cancelledor taken entirely. / | event SellOrderRemoved (uint orderId);
| event SellOrderRemoved (uint orderId);
| 6,899 |
39 | // We create a 'register' function that adds their names to our mapping | function register(string calldata name) public payable {
// Check that the domain name is NOT yet registered to a wallet address
// This 'require' statement stops other people from taking your domain
// Here, we're checking that the address of the domain you're truing to register is the same as the zero address
// The zero address in Solidity is sort of like the void where everything comes from
// When an address mapping is initialized, all entries in it point to the zero address
// So if a domain has NOT been resgietered yet, it'll point to the zero address
// require(domains[name] == address(0)); {{ DEFUNCT }}
// Reference custom Solidity error codes (see Lines: 35 - 37)
if (domains[name] != address(0)) revert AlreadyRegistered();
if (!valid(name)) revert InvalidName(name);
uint256 _price = price(name);
// Check if enough $MATIC was paid in the transaction
// Here, we check if the value of the 'msg' sent is above a certain amount
// 'value' is the amount of $MATIC sent
// 'msg' is the transaction
require(msg.value >= _price, "Not enough $MATIC paid");
// Add the 'domains' mapping variable (from Line: 67)
// A mapping is a simple datatype that 'maps' (or matches) two values
// In our case, we're mapping a string (domain name) to a wallet address
domains[name] = msg.sender;
console.log("%s has registered a domain!", msg.sender);
// Combine the name passed into the function, with the TLD
string memory _name = string(abi.encodePacked(name, ".", tld));
// Create the SVG (image) for the NFT with the name (see: Line 62)
// In other words, we're creating an SVG based on our domain
// So we split the SVG into 2 and put our domain in-between those two parts
// We use the 'encodePacked' function to turn a bunch of strings into byes, which then combines them
// This is because you can't combine strings directly in Solidity
string memory finalSvg = string(abi.encodePacked(svgPartOne, _name, svgPartTwo));
uint256 newRecordId = _tokenIds.current();
uint256 length = StringUtils.strlen(name);
string memory strLen = Strings.toString(length);
console.log("Registering %s on the contract with tokenID %d", name, newRecordId);
// Next, we create the JSON metadata of our NFT
// And we do this by combining strings and encoding as base64
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',
_name,
'", "description": "A domain on the Vibes Domain Service", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(finalSvg)),
'","length":"',
strLen,
'"}'
)
)
)
);
string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json));
console.log("\n--------------------------------------------------------");
console.log("Final tokenURI", finalTokenUri);
console.log("--------------------------------------------------------\n");
// (Lines 215 and 218) below are the magical lines that actually create our NFT
// Mint the NFT to newRecord
_safeMint(msg.sender, newRecordId);
// Set the NFTs data -- in this case, the JSON blob w/ our domain's info
_setTokenURI(newRecordId, finalTokenUri);
domains[name] = msg.sender;
// This final piece is what will allow us to retrieve the minted domains on our contract
// Ref. (Lines 90 - 98) above
names[newRecordId] = name;
_tokenIds.increment();
// Notes ##
// 'json' NFTs use JSON to store details like the name, description, attributes, and the media
// What we're doing with json is comining strings with abi.encodePacked, to make a JSON object
// We're then encoding it as a Base64 string, before setting it as the token URI
// '_tokenIds' is an object that lets us access and set our NFTs unique token number
// Each NFT has a unique id - and this helps us make sure of that
// The 'domain' variable is special because it's called a 'state variable' (contd. below)
// And it is stored permanently in the contract's storage
// Meaning: anyone who calls the register function (see Line: 146), will permanently store data related to their domain, right in our smart contract
// {{ 'msg.sender' }} is the wallet address of the person who called the function
// It's like built-in authentication - and so we know exactly who called the function because (contd. below)
// In order to even calla smart contract function, you need to sign the transaction with a valid wallet
// You can also write functions that only certain wallet address can hit
// E.g. So that only wallets that own domains, can update them
// The getAddress function (see Line: 264) below does exactly that
// It gets the wallet address of a domain owner
}
| function register(string calldata name) public payable {
// Check that the domain name is NOT yet registered to a wallet address
// This 'require' statement stops other people from taking your domain
// Here, we're checking that the address of the domain you're truing to register is the same as the zero address
// The zero address in Solidity is sort of like the void where everything comes from
// When an address mapping is initialized, all entries in it point to the zero address
// So if a domain has NOT been resgietered yet, it'll point to the zero address
// require(domains[name] == address(0)); {{ DEFUNCT }}
// Reference custom Solidity error codes (see Lines: 35 - 37)
if (domains[name] != address(0)) revert AlreadyRegistered();
if (!valid(name)) revert InvalidName(name);
uint256 _price = price(name);
// Check if enough $MATIC was paid in the transaction
// Here, we check if the value of the 'msg' sent is above a certain amount
// 'value' is the amount of $MATIC sent
// 'msg' is the transaction
require(msg.value >= _price, "Not enough $MATIC paid");
// Add the 'domains' mapping variable (from Line: 67)
// A mapping is a simple datatype that 'maps' (or matches) two values
// In our case, we're mapping a string (domain name) to a wallet address
domains[name] = msg.sender;
console.log("%s has registered a domain!", msg.sender);
// Combine the name passed into the function, with the TLD
string memory _name = string(abi.encodePacked(name, ".", tld));
// Create the SVG (image) for the NFT with the name (see: Line 62)
// In other words, we're creating an SVG based on our domain
// So we split the SVG into 2 and put our domain in-between those two parts
// We use the 'encodePacked' function to turn a bunch of strings into byes, which then combines them
// This is because you can't combine strings directly in Solidity
string memory finalSvg = string(abi.encodePacked(svgPartOne, _name, svgPartTwo));
uint256 newRecordId = _tokenIds.current();
uint256 length = StringUtils.strlen(name);
string memory strLen = Strings.toString(length);
console.log("Registering %s on the contract with tokenID %d", name, newRecordId);
// Next, we create the JSON metadata of our NFT
// And we do this by combining strings and encoding as base64
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',
_name,
'", "description": "A domain on the Vibes Domain Service", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(finalSvg)),
'","length":"',
strLen,
'"}'
)
)
)
);
string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json));
console.log("\n--------------------------------------------------------");
console.log("Final tokenURI", finalTokenUri);
console.log("--------------------------------------------------------\n");
// (Lines 215 and 218) below are the magical lines that actually create our NFT
// Mint the NFT to newRecord
_safeMint(msg.sender, newRecordId);
// Set the NFTs data -- in this case, the JSON blob w/ our domain's info
_setTokenURI(newRecordId, finalTokenUri);
domains[name] = msg.sender;
// This final piece is what will allow us to retrieve the minted domains on our contract
// Ref. (Lines 90 - 98) above
names[newRecordId] = name;
_tokenIds.increment();
// Notes ##
// 'json' NFTs use JSON to store details like the name, description, attributes, and the media
// What we're doing with json is comining strings with abi.encodePacked, to make a JSON object
// We're then encoding it as a Base64 string, before setting it as the token URI
// '_tokenIds' is an object that lets us access and set our NFTs unique token number
// Each NFT has a unique id - and this helps us make sure of that
// The 'domain' variable is special because it's called a 'state variable' (contd. below)
// And it is stored permanently in the contract's storage
// Meaning: anyone who calls the register function (see Line: 146), will permanently store data related to their domain, right in our smart contract
// {{ 'msg.sender' }} is the wallet address of the person who called the function
// It's like built-in authentication - and so we know exactly who called the function because (contd. below)
// In order to even calla smart contract function, you need to sign the transaction with a valid wallet
// You can also write functions that only certain wallet address can hit
// E.g. So that only wallets that own domains, can update them
// The getAddress function (see Line: 264) below does exactly that
// It gets the wallet address of a domain owner
}
| 46,995 |
25 | // signature validate need og billy or billy plus or billy | bool ogBillyVerified = !_isEmptyStringBytes(ogBillySignature) &&
_verifyAddressSigner(_msgSender(), _ogBillySignerAddress, ogBillySignature);
bool billyPlusVerified = !_isEmptyStringBytes(billyPlusSignature) &&
_verifyAddressSigner(_msgSender(), _billyPlusSignerAddress, billyPlusSignature);
bool billyVerified = !_isEmptyStringBytes(billySignature) &&
_verifyAddressSigner(_msgSender(), _billySignerAddress, billySignature);
require(ogBillyVerified || billyPlusVerified || billyVerified, "mintBilly: signature invalid");
uint256 mintAvailableCount = getMintAvailableCount(
_msgSender(),
| bool ogBillyVerified = !_isEmptyStringBytes(ogBillySignature) &&
_verifyAddressSigner(_msgSender(), _ogBillySignerAddress, ogBillySignature);
bool billyPlusVerified = !_isEmptyStringBytes(billyPlusSignature) &&
_verifyAddressSigner(_msgSender(), _billyPlusSignerAddress, billyPlusSignature);
bool billyVerified = !_isEmptyStringBytes(billySignature) &&
_verifyAddressSigner(_msgSender(), _billySignerAddress, billySignature);
require(ogBillyVerified || billyPlusVerified || billyVerified, "mintBilly: signature invalid");
uint256 mintAvailableCount = getMintAvailableCount(
_msgSender(),
| 26,840 |
44 | // Allowes access to the uint variables saved in the apiUintVars under the requestDetails structfor the requestId specified _requestId to look up _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name isthe variables/strings used to save the data in the mapping. The variables names arecommented out under the apiUintVars under the requestDetails structreturn uint value of the apiUintVars specified in _data for the requestId specified / | function getRequestUintVars(uint256 _requestId, bytes32 _data)
| function getRequestUintVars(uint256 _requestId, bytes32 _data)
| 18,358 |
172 | // If the token is redeployed, the version is increased to prevent a permit signature being used on both token instances. | string public version;
| string public version;
| 31,519 |
13 | // Ensures that the caller is a cross-chain message from the other bridge. | modifier onlyOtherBridge() {
require(
msg.sender == address(MESSENGER) &&
MESSENGER.xDomainMessageSender() == address(OTHER_BRIDGE),
"StandardBridge: function can only be called from the other bridge"
);
_;
}
| modifier onlyOtherBridge() {
require(
msg.sender == address(MESSENGER) &&
MESSENGER.xDomainMessageSender() == address(OTHER_BRIDGE),
"StandardBridge: function can only be called from the other bridge"
);
_;
}
| 11,116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.