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
|
---|---|---|---|---|
150 | // / | newShareRate = SHARE_RATE_MAX;
| newShareRate = SHARE_RATE_MAX;
| 579 |
89 | // Queued debt amount [wad] | uint256 public override queuedDebt;
| uint256 public override queuedDebt;
| 37,388 |
30 | // If the recipient had bid for the Sketch, remove the bid and make it possible to refund its value | Bid storage bid = sketchIndexToHighestBid[sketchIndex];
if (bid.bidder == to) {
accountToWithdrawableValue[to] += bid.value;
sketchIndexToHighestBid[sketchIndex] = Bid(false, sketchIndex, 0x0, 0);
}
| Bid storage bid = sketchIndexToHighestBid[sketchIndex];
if (bid.bidder == to) {
accountToWithdrawableValue[to] += bid.value;
sketchIndexToHighestBid[sketchIndex] = Bid(false, sketchIndex, 0x0, 0);
}
| 15,877 |
293 | // Publish allows for setting the link, image of the ad./ unit that is identified by the idx which was returned during the buy step./ The link and image must be full web3-recognizeable URLs, such as:/- bzz:a5c10851ef054c268a2438f10a21f6efe3dc3dcdcc2ea0e6a1a7a38bf8c91e23/- bzz:mydomain.eth/ad.png/- https:cdn.mydomain.com/ad.png/ Images should be valid PNG. | function publish(uint _idx, string calldata _link, string calldata _image, string calldata _title, bool _NSFW) public {
Ad storage ad = ads[_idx];
require(msg.sender == ad.owner,"Sender is not slot owner!");
ad.link = _link;
ad.image = _image;
ad.title = _title;
ad.NSFW = _NSFW;
emit Publish(_idx, ad.link, ad.image, ad.title, ad.NSFW || ad.forceNSFW);
}
| function publish(uint _idx, string calldata _link, string calldata _image, string calldata _title, bool _NSFW) public {
Ad storage ad = ads[_idx];
require(msg.sender == ad.owner,"Sender is not slot owner!");
ad.link = _link;
ad.image = _image;
ad.title = _title;
ad.NSFW = _NSFW;
emit Publish(_idx, ad.link, ad.image, ad.title, ad.NSFW || ad.forceNSFW);
}
| 49,162 |
6 | // Retrieve raw trait IDs for a given seed value. | function getStartingTraitsBySeed(uint256 seed)
public
pure
returns (Traits memory)
| function getStartingTraitsBySeed(uint256 seed)
public
pure
returns (Traits memory)
| 6,562 |
30 | // prod accounts | address private _accountFee = 0x7554CEA927C9D9b0329470d73aD4D03533Ce9538;
address private _accountSales = 0xA267ffeAD14B0F302e6AA10f156Ad41D17d2278D;
| address private _accountFee = 0x7554CEA927C9D9b0329470d73aD4D03533Ce9538;
address private _accountSales = 0xA267ffeAD14B0F302e6AA10f156Ad41D17d2278D;
| 11,794 |
224 | // Set bonusMultiplier. Can only be called by the owner. | function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
| function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
| 38,764 |
12 | // Validate Content Hash alone of a student _transcriptHash - Transcript Hash of the documentreturn Returns true if validation is successful / | function validateTranscriptHash(Document storage self, bytes32 _transcriptHash) public view returns(bool) {
bytes32 transcriptHash = self.transcriptHash;
return transcriptHash == _transcriptHash;
}
| function validateTranscriptHash(Document storage self, bytes32 _transcriptHash) public view returns(bool) {
bytes32 transcriptHash = self.transcriptHash;
return transcriptHash == _transcriptHash;
}
| 45,204 |
3 | // Sets a new controller. address_ Address of the controller. / | function setController(address address_) external onlyOwner {
require(
address_ != address(0x0),
"controller address cannot be the null address"
);
emit Controller(ticker, address(controller), address_);
controller = SmartController(address_);
require(
controller.isFrontend(address(this)),
"controller frontend does not point back"
);
require(
controller.ticker() == ticker,
"ticker does not match controller ticket"
);
}
| function setController(address address_) external onlyOwner {
require(
address_ != address(0x0),
"controller address cannot be the null address"
);
emit Controller(ticker, address(controller), address_);
controller = SmartController(address_);
require(
controller.isFrontend(address(this)),
"controller frontend does not point back"
);
require(
controller.ticker() == ticker,
"ticker does not match controller ticket"
);
}
| 18,500 |
10 | // ============================== ERC20 | event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
| event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
| 3,648 |
60 | // The struct consists of ERC20-style token metadata. | struct ERC20Metadata {
string name;
string symbol;
uint8 decimals;
}
| struct ERC20Metadata {
string name;
string symbol;
uint8 decimals;
}
| 32,379 |
11 | // Emitted after a successful token claim/to recipient of claim/amount of tokens claimed | event Claim(address indexed to, uint256 amount);
| event Claim(address indexed to, uint256 amount);
| 2,927 |
67 | // Retrieve the dividend balance of any single address. / | function dividendsOf(address _customerAddress) public view returns (uint) {
return (uint) ((int)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
| function dividendsOf(address _customerAddress) public view returns (uint) {
return (uint) ((int)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
| 63,767 |
77 | // this should never happen | require(_payableGovernanceAddresses.length == _payableGovernanceShares.length, "Payable governance length mismatch!");
| require(_payableGovernanceAddresses.length == _payableGovernanceShares.length, "Payable governance length mismatch!");
| 36,462 |
1 | // Returns the address of the current pending owner. / | address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
| address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
| 31,624 |
10 | // burn the LP | sAMMUsdcDei.burn(me);
console.log("[+] my USDC balance: %s", usdc.balanceOf(me));
console.log("[+] my DEI balance: %s", dei.balanceOf(me));
console.log("[+] my LP token balance: %s\n", sAMMUsdcDei.balanceOf(me));
| sAMMUsdcDei.burn(me);
console.log("[+] my USDC balance: %s", usdc.balanceOf(me));
console.log("[+] my DEI balance: %s", dei.balanceOf(me));
console.log("[+] my LP token balance: %s\n", sAMMUsdcDei.balanceOf(me));
| 43,446 |
96 | // maxTransactionAmount | maxTransactionAmount = 1000000000000000000000000;
maxWallet = 20000000000000000000000;
swapTokensAtAmount = totalSupply * 10 / 2500;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
| maxTransactionAmount = 1000000000000000000000000;
maxWallet = 20000000000000000000000;
swapTokensAtAmount = totalSupply * 10 / 2500;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
| 8,917 |
10 | // Enables or disables approval for a third party ("operator") to manage all of`msg.sender`'s assets. It also emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval. / | function setApprovalForAll(
| function setApprovalForAll(
| 48,311 |
105 | // Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor)return Calculate the numberOfWeeks since last mint rounded down to 1 week / | function weeksSinceLastIssuance() public view returns (uint) {
// Get weeks since lastMintEvent
// If lastMintEvent not set or 0, then start from inflation start date.
uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);
return timeDiff.div(MINT_PERIOD_DURATION);
}
| function weeksSinceLastIssuance() public view returns (uint) {
// Get weeks since lastMintEvent
// If lastMintEvent not set or 0, then start from inflation start date.
uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);
return timeDiff.div(MINT_PERIOD_DURATION);
}
| 10,431 |
95 | // The old address, can be address(0). oldAddress and newAddress cannot both equal address(0). | address oldAddress;
| address oldAddress;
| 56,728 |
21 | // mappings | mapping(address => uint256) public _balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
| mapping(address => uint256) public _balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
| 9,644 |
53 | // Change Presale Publicsale end time | function changeEndTime(uint256 _endTime) public onlyOwner {
require(endTime > startTime);
endTime = _endTime;
}
| function changeEndTime(uint256 _endTime) public onlyOwner {
require(endTime > startTime);
endTime = _endTime;
}
| 21,340 |
49 | // Accounts for rounding errors when unwrapping wstETH | amount = amount.sub(
IERC20(steth).balanceOf(address(this)).sub(stethBalance)
);
| amount = amount.sub(
IERC20(steth).balanceOf(address(this)).sub(stethBalance)
);
| 59,252 |
6 | // The entire array was composed of a single value. | ret = createUniqueArray(input, 1);
return ret;
| ret = createUniqueArray(input, 1);
return ret;
| 40,630 |
38 | // raid character (token 0) live in 7 and have random special skills | if (newNarcoId==0){
narcos[0].homeLocation=7; // in vice island
narcos[0].skills[4]=800; // defense
narcos[0].skills[5]=65535; // carry
}
| if (newNarcoId==0){
narcos[0].homeLocation=7; // in vice island
narcos[0].skills[4]=800; // defense
narcos[0].skills[5]=65535; // carry
}
| 16,209 |
25 | // Interface for Project data contracts/ | contract ProjectManager is ErrorCodes, Util, ProjectState, ProjectEvent, BidState {
Project[] projects;
uint bidId; // unique identifier for bids
/*
note on mapping to array index:
a non existing mapping will return 0, so 0 should not be a valid value in a map,
otherwise exists() will not work
*/
mapping (bytes32 => uint) nameToIndexMap;
/**
* Constructor
*/
function ProjectManager() {
projects.length = 1; // see above note
bidId = block.number;
}
function exists(string name) returns (bool) {
return nameToIndexMap[b32(name)] != 0;
}
function getProject(string name) returns (address) {
uint index = nameToIndexMap[b32(name)];
return projects[index];
}
/*
string addressStreet,
string addressCity,
string addressState,
string addressZip
*/
// addressStreet,
// addressCity,
// addressState,
// addressZip
function createProject(
string name,
string buyer,
string description,
string spec,
uint price,
uint created,
uint targetDelivery
) returns (ErrorCodes) {
// name must be < 32 bytes
if (bytes(name).length > 32) return ErrorCodes.ERROR;
// fail if username exists
if (exists(name)) return ErrorCodes.EXISTS;
// add project
uint index = projects.length;
nameToIndexMap[b32(name)] = index;
projects.push(new Project(
name,
buyer,
description,
spec,
price,
created,
targetDelivery
));
return ErrorCodes.SUCCESS;
}
function createBid(string name, string supplier, uint amount) returns (ErrorCodes, uint) {
// fail if project name not found
if (!exists(name)) return (ErrorCodes.NOT_FOUND, 0);
// create bid
bidId++; // increment the unique id
Bid bid = new Bid(bidId, name, supplier, amount);
return (ErrorCodes.SUCCESS, bidId);
}
function settleProject(string name, address supplierAddress, address bidAddress) returns (ErrorCodes) {
// validity
if (!exists(name)) return (ErrorCodes.NOT_FOUND);
// set project state
address projectAddress = getProject(name);
var (errorCode, state) = handleEvent(projectAddress, ProjectEvent.RECEIVE);
if (errorCode != ErrorCodes.SUCCESS) return errorCode;
// settle
Bid bid = Bid(bidAddress);
return bid.settle(supplierAddress);
}
/**
* handleEvent - transition project to a new state based on incoming event
*/
function handleEvent(address projectAddress, ProjectEvent projectEvent) returns (ErrorCodes, ProjectState) {
Project project = Project(projectAddress);
ProjectState state = project.getState();
// check transition
var (errorCode, newState) = fsm(state, projectEvent);
// event is not valid in current state
if (errorCode != ErrorCodes.SUCCESS) {
return (errorCode, state);
}
// use the new state
project.setState(newState);
return (ErrorCodes.SUCCESS, newState);
}
function fsm(ProjectState state, ProjectEvent projectEvent) returns (ErrorCodes, ProjectState) {
// NULL
if (state == ProjectState.NULL)
return (ErrorCodes.ERROR, state);
// OPEN
if (state == ProjectState.OPEN) {
if (projectEvent == ProjectEvent.ACCEPT)
return (ErrorCodes.SUCCESS, ProjectState.PRODUCTION);
}
// PRODUCTION
if (state == ProjectState.PRODUCTION) {
if (projectEvent == ProjectEvent.DELIVER)
return (ErrorCodes.SUCCESS, ProjectState.INTRANSIT);
}
// INTRANSIT
if (state == ProjectState.INTRANSIT) {
if (projectEvent == ProjectEvent.RECEIVE)
return (ErrorCodes.SUCCESS, ProjectState.RECEIVED);
}
return (ErrorCodes.ERROR, state);
}
}
| contract ProjectManager is ErrorCodes, Util, ProjectState, ProjectEvent, BidState {
Project[] projects;
uint bidId; // unique identifier for bids
/*
note on mapping to array index:
a non existing mapping will return 0, so 0 should not be a valid value in a map,
otherwise exists() will not work
*/
mapping (bytes32 => uint) nameToIndexMap;
/**
* Constructor
*/
function ProjectManager() {
projects.length = 1; // see above note
bidId = block.number;
}
function exists(string name) returns (bool) {
return nameToIndexMap[b32(name)] != 0;
}
function getProject(string name) returns (address) {
uint index = nameToIndexMap[b32(name)];
return projects[index];
}
/*
string addressStreet,
string addressCity,
string addressState,
string addressZip
*/
// addressStreet,
// addressCity,
// addressState,
// addressZip
function createProject(
string name,
string buyer,
string description,
string spec,
uint price,
uint created,
uint targetDelivery
) returns (ErrorCodes) {
// name must be < 32 bytes
if (bytes(name).length > 32) return ErrorCodes.ERROR;
// fail if username exists
if (exists(name)) return ErrorCodes.EXISTS;
// add project
uint index = projects.length;
nameToIndexMap[b32(name)] = index;
projects.push(new Project(
name,
buyer,
description,
spec,
price,
created,
targetDelivery
));
return ErrorCodes.SUCCESS;
}
function createBid(string name, string supplier, uint amount) returns (ErrorCodes, uint) {
// fail if project name not found
if (!exists(name)) return (ErrorCodes.NOT_FOUND, 0);
// create bid
bidId++; // increment the unique id
Bid bid = new Bid(bidId, name, supplier, amount);
return (ErrorCodes.SUCCESS, bidId);
}
function settleProject(string name, address supplierAddress, address bidAddress) returns (ErrorCodes) {
// validity
if (!exists(name)) return (ErrorCodes.NOT_FOUND);
// set project state
address projectAddress = getProject(name);
var (errorCode, state) = handleEvent(projectAddress, ProjectEvent.RECEIVE);
if (errorCode != ErrorCodes.SUCCESS) return errorCode;
// settle
Bid bid = Bid(bidAddress);
return bid.settle(supplierAddress);
}
/**
* handleEvent - transition project to a new state based on incoming event
*/
function handleEvent(address projectAddress, ProjectEvent projectEvent) returns (ErrorCodes, ProjectState) {
Project project = Project(projectAddress);
ProjectState state = project.getState();
// check transition
var (errorCode, newState) = fsm(state, projectEvent);
// event is not valid in current state
if (errorCode != ErrorCodes.SUCCESS) {
return (errorCode, state);
}
// use the new state
project.setState(newState);
return (ErrorCodes.SUCCESS, newState);
}
function fsm(ProjectState state, ProjectEvent projectEvent) returns (ErrorCodes, ProjectState) {
// NULL
if (state == ProjectState.NULL)
return (ErrorCodes.ERROR, state);
// OPEN
if (state == ProjectState.OPEN) {
if (projectEvent == ProjectEvent.ACCEPT)
return (ErrorCodes.SUCCESS, ProjectState.PRODUCTION);
}
// PRODUCTION
if (state == ProjectState.PRODUCTION) {
if (projectEvent == ProjectEvent.DELIVER)
return (ErrorCodes.SUCCESS, ProjectState.INTRANSIT);
}
// INTRANSIT
if (state == ProjectState.INTRANSIT) {
if (projectEvent == ProjectEvent.RECEIVE)
return (ErrorCodes.SUCCESS, ProjectState.RECEIVED);
}
return (ErrorCodes.ERROR, state);
}
}
| 32,352 |
13 | // Finally, purchase tokens. | purchaseTokens(msg.value, _referredBy);
| purchaseTokens(msg.value, _referredBy);
| 16,515 |
100 | // set warmup period in epoch's numbers for new stakers _warmupPeriod uint / | function setWarmup( uint _warmupPeriod ) external onlyOwner {
warmupPeriod = _warmupPeriod;
emit LogWarmupPeriod(_warmupPeriod);
}
| function setWarmup( uint _warmupPeriod ) external onlyOwner {
warmupPeriod = _warmupPeriod;
emit LogWarmupPeriod(_warmupPeriod);
}
| 26,981 |
3 | // Checks that _data is valid (not calling anything it shouldn't) | require(Util.getSig(_data) == preSaleSTO.getInitFunction(), "Invalid data");
| require(Util.getSig(_data) == preSaleSTO.getInitFunction(), "Invalid data");
| 8,456 |
4 | // Check for batch minting | if (quantity > 1) {
for (uint16 i = quantity; i > 0; i--) {
containerInfo.value.deployedAt.safeMint(purchaseCaller, containerInfo.value.idCounter);
containerInfo.value.idCounter++;
}
| if (quantity > 1) {
for (uint16 i = quantity; i > 0; i--) {
containerInfo.value.deployedAt.safeMint(purchaseCaller, containerInfo.value.idCounter);
containerInfo.value.idCounter++;
}
| 30,386 |
85 | // 客户查找自己已购买的商品数组 | function getGoodsByCustomer(string _phone)constant returns(bytes32[]) {
bytes32 tempPhone = stringToBytes32(_phone);
address tempCustomerAddr = customerPhone[tempPhone];
return customer[tempCustomerAddr].buyGoods;
}
| function getGoodsByCustomer(string _phone)constant returns(bytes32[]) {
bytes32 tempPhone = stringToBytes32(_phone);
address tempCustomerAddr = customerPhone[tempPhone];
return customer[tempCustomerAddr].buyGoods;
}
| 25,132 |
33 | // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. | uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version870 = 5; //inject NONSTANDARD NAMING
| uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version870 = 5; //inject NONSTANDARD NAMING
| 14,285 |
215 | // Gets the amount of an underlying token that `amount` of `yieldToken` is exchangeable for.//yieldToken The address of the yield token./amount The amount of yield tokens.// return The amount of underlying tokens. | function convertYieldTokensToUnderlying(address yieldToken, uint256 amount) public view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * adapter.price() / 10 ** yieldTokenParams.decimals;
}
| function convertYieldTokensToUnderlying(address yieldToken, uint256 amount) public view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * adapter.price() / 10 ** yieldTokenParams.decimals;
}
| 6,165 |
1 | // Supply & Cost | uint256 public mintCost = 0.003 ether;
uint256 public maxSupply = 6665;
| uint256 public mintCost = 0.003 ether;
uint256 public maxSupply = 6665;
| 27,406 |
393 | // Emitted when borrow cap for a dToken is changed | event NewBorrowCap(DToken indexed dToken, uint newBorrowCap);
| event NewBorrowCap(DToken indexed dToken, uint newBorrowCap);
| 13,381 |
37 | // 允许发行方提取 BIX | function withdraw_bix() public {
require(msg.sender == DepositAddress);
require(AllowWithdrawAmount > 0);
BixToken.transfer(msg.sender, AllowWithdrawAmount);
// 提取完后 将额度设置为 0
AllowWithdrawAmount = 0;
emit WithdrawBix(AllowWithdrawAmount);
}
| function withdraw_bix() public {
require(msg.sender == DepositAddress);
require(AllowWithdrawAmount > 0);
BixToken.transfer(msg.sender, AllowWithdrawAmount);
// 提取完后 将额度设置为 0
AllowWithdrawAmount = 0;
emit WithdrawBix(AllowWithdrawAmount);
}
| 46,888 |
44 | // issue debit dolllars | _balanceOf[msgSender] = _balanceOf[msgSender].add(DebitDollarDepositAmount);
_totalSupply = _totalSupply.add(DebitDollarDepositAmount);
emit Transfer(address(0), msgSender, DebitDollarDepositAmount);
return "Debit Dollars issued successfully";
| _balanceOf[msgSender] = _balanceOf[msgSender].add(DebitDollarDepositAmount);
_totalSupply = _totalSupply.add(DebitDollarDepositAmount);
emit Transfer(address(0), msgSender, DebitDollarDepositAmount);
return "Debit Dollars issued successfully";
| 13,486 |
415 | // -1 | t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
| t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
| 16,184 |
76 | // restore dynamicFee after buyback | _liquidityFee = dynamicFee;
| _liquidityFee = dynamicFee;
| 39,642 |
192 | // Function a contract must implement in order to receive ownership of a position via thetransferPosition function or the atomic-assign to the "owner" field when opening a position. fromAddress of the previous ownerpositionIdUnique ID of the positionreturn This address to keep ownership, a different address to pass-on ownership / | function receivePositionOwnership(
address from,
bytes32 positionId
)
external
| function receivePositionOwnership(
address from,
bytes32 positionId
)
external
| 72,264 |
43 | // 0x43a61a8e == rootOwnerOf(uint256) | calldata = abi.encodeWithSelector(0x43a61a8e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
| calldata = abi.encodeWithSelector(0x43a61a8e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
| 634 |
18 | // Throws if called by any account which does not have MINTER_ROLE. / | modifier onlyMinter {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_;
}
| modifier onlyMinter {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_;
}
| 13,165 |
48 | // Admin can give '_account' address operator privileges. _account address that should be given operator privileges. / | function addOperator(address _account) public onlyAdminOrRelay {
_addOperator(_account);
}
| function addOperator(address _account) public onlyAdminOrRelay {
_addOperator(_account);
}
| 24,484 |
101 | // add a new auction to exchange, deposit the bonds in question into exchange contract | function addAuction(AUCTION memory _auction) public override returns(bool){
require(contract_is_active==true,"contract is not active");
_auction.auctionTimestamp=now;
require(_auction.auctionDuration>=24*60*60,"timestamp error");
require(_auction.auctionDuration<=24*30*60*60,"timestamp error");
_auction.auctionStatus = true;
require(_auction.bondClass.length == _auction.bondNonce.length && _auction.bondNonce.length == _auction.bondAmount.length,"ERC659:input error");
require(_addAuction(_auction)==true,"can't create more auction");
require(_addCustody(_auction)==true,"can't move to custody");
return(true);
}
| function addAuction(AUCTION memory _auction) public override returns(bool){
require(contract_is_active==true,"contract is not active");
_auction.auctionTimestamp=now;
require(_auction.auctionDuration>=24*60*60,"timestamp error");
require(_auction.auctionDuration<=24*30*60*60,"timestamp error");
_auction.auctionStatus = true;
require(_auction.bondClass.length == _auction.bondNonce.length && _auction.bondNonce.length == _auction.bondAmount.length,"ERC659:input error");
require(_addAuction(_auction)==true,"can't create more auction");
require(_addCustody(_auction)==true,"can't move to custody");
return(true);
}
| 14,384 |
3 | // See {IDigitalReserve-strategyTokenCount}. / | function strategyTokenCount() public view override returns (uint256) {
return _strategyTokens.length;
}
| function strategyTokenCount() public view override returns (uint256) {
return _strategyTokens.length;
}
| 71,872 |
47 | // Changes The Price Of A Fixed Price Sale SaleIndex The Sale Index To Edit Price The Sale Price (IN WEI) / | function __ChangeFixedPrice(uint SaleIndex, uint Price) external onlyAdmin { FixedPriceSales[SaleIndex]._Price = Price; }
/**
* @dev Changes The MintPass ProjectID
* @param SaleIndex The Sale Index To Edit
* @param MintPassProjectID The Mint Pass ProjectID
*/
function __ChangeFixedPriceMintPassProjectID(uint SaleIndex, uint MintPassProjectID) external onlyAdmin
{
FixedPriceSales[SaleIndex]._MintPassProjectID = MintPassProjectID;
}
| function __ChangeFixedPrice(uint SaleIndex, uint Price) external onlyAdmin { FixedPriceSales[SaleIndex]._Price = Price; }
/**
* @dev Changes The MintPass ProjectID
* @param SaleIndex The Sale Index To Edit
* @param MintPassProjectID The Mint Pass ProjectID
*/
function __ChangeFixedPriceMintPassProjectID(uint SaleIndex, uint MintPassProjectID) external onlyAdmin
{
FixedPriceSales[SaleIndex]._MintPassProjectID = MintPassProjectID;
}
| 19,805 |
6 | // modified matchAndTransfer method src/ExchangeV2Core.sol were thebase currency funds are transfered to orderRight.maker or the orderRight.taker / | function matchAndTransferAuction(LibOrder.Order memory orderLeft, LibOrder.Order memory orderRight, uint amountFromAuction) internal {
(LibAsset.AssetType memory makeMatch, LibAsset.AssetType memory takeMatch) = matchAssets(orderLeft, orderRight);
bytes32 leftOrderKeyHash = LibOrder.hashKey(orderLeft);
bytes32 rightOrderKeyHash = LibOrder.hashKey(orderRight);
uint leftOrderFill = fills[leftOrderKeyHash];
uint rightOrderFill = fills[rightOrderKeyHash];
LibFill.FillResult memory fill = LibFill.fillOrder(orderLeft, orderRight, leftOrderFill, rightOrderFill);
require(fill.takeValue > 0, "nothing to fill");
(uint totalMakeValue, uint totalTakeValue) = doTransfers(makeMatch, takeMatch, fill, orderLeft, orderRight);
if (makeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(amountFromAuction >= totalMakeValue, "makeMatch: not enough MATIC");
if (amountFromAuction > totalMakeValue) {
address(msg.sender).transferEth(amountFromAuction - totalMakeValue);
}
} else if (takeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(amountFromAuction >= totalTakeValue, "takeMatch: not enough MATIC");
if (amountFromAuction > totalTakeValue) {
address(msg.sender).transferEth(amountFromAuction - totalMakeValue);
}
}
if (address(this) != orderLeft.maker) {
fills[leftOrderKeyHash] = leftOrderFill + fill.takeValue;
}
if (address(this) != orderRight.maker) {
fills[rightOrderKeyHash] = rightOrderFill + fill.makeValue;
}
emit OrderFilled(leftOrderKeyHash, rightOrderKeyHash, orderLeft.maker, orderRight.maker, fill.takeValue, fill.makeValue);
}
| function matchAndTransferAuction(LibOrder.Order memory orderLeft, LibOrder.Order memory orderRight, uint amountFromAuction) internal {
(LibAsset.AssetType memory makeMatch, LibAsset.AssetType memory takeMatch) = matchAssets(orderLeft, orderRight);
bytes32 leftOrderKeyHash = LibOrder.hashKey(orderLeft);
bytes32 rightOrderKeyHash = LibOrder.hashKey(orderRight);
uint leftOrderFill = fills[leftOrderKeyHash];
uint rightOrderFill = fills[rightOrderKeyHash];
LibFill.FillResult memory fill = LibFill.fillOrder(orderLeft, orderRight, leftOrderFill, rightOrderFill);
require(fill.takeValue > 0, "nothing to fill");
(uint totalMakeValue, uint totalTakeValue) = doTransfers(makeMatch, takeMatch, fill, orderLeft, orderRight);
if (makeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(amountFromAuction >= totalMakeValue, "makeMatch: not enough MATIC");
if (amountFromAuction > totalMakeValue) {
address(msg.sender).transferEth(amountFromAuction - totalMakeValue);
}
} else if (takeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(amountFromAuction >= totalTakeValue, "takeMatch: not enough MATIC");
if (amountFromAuction > totalTakeValue) {
address(msg.sender).transferEth(amountFromAuction - totalMakeValue);
}
}
if (address(this) != orderLeft.maker) {
fills[leftOrderKeyHash] = leftOrderFill + fill.takeValue;
}
if (address(this) != orderRight.maker) {
fills[rightOrderKeyHash] = rightOrderFill + fill.makeValue;
}
emit OrderFilled(leftOrderKeyHash, rightOrderKeyHash, orderLeft.maker, orderRight.maker, fill.takeValue, fill.makeValue);
}
| 30,902 |
84 | // Extension of ERC20 standard designed for simple 'personal token' deployments. / | contract PersonalERC20 is MinterRole, ERC20Burnable, ERC20Pausable {
string private _name;
string private _symbol;
uint8 private _decimals;
address private _owner;
/**
* @dev Sets the values for `name`, `symbol`, 'init', 'owner'. All four of
* these values are immutable: they can only be set once during
* construction. Decimals are defaulted to '18', per ERC20 norms, imitating
* the relationship between Ether and Wei.
*/
constructor (string memory name, string memory symbol, uint256 init, address owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_balances[_owner] = init; // provides initial deposit to owner set by constructor
_totalSupply = init; // initializes totalSupply with initial deposit
_addMinter(_owner);
_addPauser(_owner);
emit Transfer(address(0), _owner, _totalSupply);
}
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token's initial owner.
*/
function owner() public view returns (address) {
return _owner;
}
} | contract PersonalERC20 is MinterRole, ERC20Burnable, ERC20Pausable {
string private _name;
string private _symbol;
uint8 private _decimals;
address private _owner;
/**
* @dev Sets the values for `name`, `symbol`, 'init', 'owner'. All four of
* these values are immutable: they can only be set once during
* construction. Decimals are defaulted to '18', per ERC20 norms, imitating
* the relationship between Ether and Wei.
*/
constructor (string memory name, string memory symbol, uint256 init, address owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_balances[_owner] = init; // provides initial deposit to owner set by constructor
_totalSupply = init; // initializes totalSupply with initial deposit
_addMinter(_owner);
_addPauser(_owner);
emit Transfer(address(0), _owner, _totalSupply);
}
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token's initial owner.
*/
function owner() public view returns (address) {
return _owner;
}
} | 32,447 |
292 | // mumbai | registry := 0xff7Ca10aF37178BdD056628eF42fD7F799fAc77c
| registry := 0xff7Ca10aF37178BdD056628eF42fD7F799fAc77c
| 62,721 |
80 | // Call the implementation. out and outsize are 0 because we don't know the size yet. | let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
| let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
| 59,981 |
79 | // The Rate of SWAMPWOLF token by BNB ( 2430 SWAMPWOLF / 1 BNB ) | uint256 public rate = 243e1;
| uint256 public rate = 243e1;
| 8,149 |
102 | // Safely transfers 'tokenId' token from 'from' to 'to'. Requirements: - 'from' cannot be the zero address.- 'to' cannot be the zero address.- 'tokenId' token must exist and be owned by 'from'. | * - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers 'tokenId' token from 'from' to 'to', checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must exist and be owned by 'from'.
* - If the caller is not 'from', it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers 'tokenId' token from 'from' to 'to'.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must be owned by 'from'.
* - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to 'to' to transfer 'tokenId' token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - 'tokenId' must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove 'operator' as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The 'operator' cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for 'tokenId' token.
*
* Requirements:
*
* - 'tokenId' must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the 'operator' is allowed to manage all of the assets of 'owner'.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
| * - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers 'tokenId' token from 'from' to 'to', checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must exist and be owned by 'from'.
* - If the caller is not 'from', it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers 'tokenId' token from 'from' to 'to'.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must be owned by 'from'.
* - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to 'to' to transfer 'tokenId' token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - 'tokenId' must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove 'operator' as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The 'operator' cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for 'tokenId' token.
*
* Requirements:
*
* - 'tokenId' must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the 'operator' is allowed to manage all of the assets of 'owner'.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
| 25,948 |
6 | // Return filled amount of an order.order Order object.returnfilledAmountThe amount of already filled. / | function getOrderFilledAmount(Order memory order) public view returns (int256 filledAmount) {
bytes32 orderHash = order.getOrderHash();
filledAmount = _orderFilled[orderHash];
}
| function getOrderFilledAmount(Order memory order) public view returns (int256 filledAmount) {
bytes32 orderHash = order.getOrderHash();
filledAmount = _orderFilled[orderHash];
}
| 2,902 |
152 | // add addresses to whitelist / | function addAddressesToWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
whitelist[_addresses[i]] = true;
emit WhitelistedAddressAdded(_addresses[i]);
}
}
| function addAddressesToWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
whitelist[_addresses[i]] = true;
emit WhitelistedAddressAdded(_addresses[i]);
}
}
| 29,890 |
147 | // Reduce number of external calls (SLOADs stay the same) | VaultAPI[] private _cachedVaults;
RegistryAPI public registry;
| VaultAPI[] private _cachedVaults;
RegistryAPI public registry;
| 41,402 |
8 | // Return amount of tokens that {account} gets during rebase Used both internally and externally to calculate the rebase amount account is an address of token holder to calculate forreturn amount of tokens that player could get / | function rebaseOwing (address account) public view returns(uint256) {
Account memory _account = _accounts[account];
uint256 newRebase = totalRebase.sub(_account.lastRebase);
uint256 proportion = _account.balance.mul(newRebase);
| function rebaseOwing (address account) public view returns(uint256) {
Account memory _account = _accounts[account];
uint256 newRebase = totalRebase.sub(_account.lastRebase);
uint256 proportion = _account.balance.mul(newRebase);
| 45,508 |
340 | // calculate the total underlaying 'want' held by the strat. | function balanceOf() public view returns (uint256) {
return balanceOfWant() + balanceOfPool();
}
| function balanceOf() public view returns (uint256) {
return balanceOfWant() + balanceOfPool();
}
| 13,692 |
2 | // Ensure that the seller has enough balance to sell | require(address(msg.sender).balance > price, "Not enough balance to sell");
| require(address(msg.sender).balance > price, "Not enough balance to sell");
| 8,449 |
92 | // Function to mint tokens. | * NOTE: restricting access to owner only. See {BEP20Mintable-mint}.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function _mint(address account, uint256 amount) internal override onlyOwner {
super._mint(account, amount);
}
| * NOTE: restricting access to owner only. See {BEP20Mintable-mint}.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function _mint(address account, uint256 amount) internal override onlyOwner {
super._mint(account, amount);
}
| 15,165 |
54 | // Bytes written to out so far | uint256 outcnt;
| uint256 outcnt;
| 79,738 |
401 | // If collateralSlice == collateralToSell => auction completed => debtFloor doesn't matter | uint256 _auctionDebtFloor = vaults[auction.vault].auctionDebtFloor;
if (debt - owe < _auctionDebtFloor) {
| uint256 _auctionDebtFloor = vaults[auction.vault].auctionDebtFloor;
if (debt - owe < _auctionDebtFloor) {
| 33,975 |
43 | // TODO: remove before hook unless needed | _beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
| _beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
| 69,219 |
128 | // cToken address on Compound | address cToken;
| address cToken;
| 54,458 |
129 | // Asset id to be sold | uint64 assetId;
| uint64 assetId;
| 69,028 |
2 | // Encodes the argument json bytes into base64-data uri format json raw json to base64 and turn into a data-uri / | function encodeMetadata(bytes memory json) public pure returns (string memory) {
return string(abi.encodePacked("data:application/json;base64,", base64Encode(json)));
}
| function encodeMetadata(bytes memory json) public pure returns (string memory) {
return string(abi.encodePacked("data:application/json;base64,", base64Encode(json)));
}
| 13,584 |
65 | // See {ERC2981-_feeDenominator}. / | function feeDenominator() external pure returns (uint96) {
return _feeDenominator();
}
| function feeDenominator() external pure returns (uint96) {
return _feeDenominator();
}
| 19,119 |
3 | // A member decided that they did not want to be part of the protocol | event MemberRageQuit(uint256 indexed knotIndex);
| event MemberRageQuit(uint256 indexed knotIndex);
| 17,087 |
170 | // SparkleTokenCrowdsale Contract contructor / | constructor(ERC20 _tokenAddress, uint256 _tokenRate, uint256 _tokenCap, uint256 _startTime, uint256 _endTime, address _depositWallet, bool _kycRequired)
| constructor(ERC20 _tokenAddress, uint256 _tokenRate, uint256 _tokenCap, uint256 _startTime, uint256 _endTime, address _depositWallet, bool _kycRequired)
| 25,667 |
56 | // Fetch the BoostOffer for the delegator | BoostOffer storage offer = offers[userIndex[delegator]];
| BoostOffer storage offer = offers[userIndex[delegator]];
| 32,784 |
154 | // mapping (address => bytes32) private revokingHash_; | mapping (bytes32 => OCSPRevocation) private cbRevoking_;
| mapping (bytes32 => OCSPRevocation) private cbRevoking_;
| 48,070 |
111 | // Bird's BErc20WBTCDelegator Contract BTokens which wrap an EIP-20 underlying and delegate to an implementation / | contract BErc20WBTCDelegator is BTokenInterface, BErc20Interface, BDelegatorInterface {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param bController_ The address of the BController
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(address underlying_,
BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address implementation_,
bytes memory becomeImplementationData) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)",
underlying_,
bController_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_));
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
// Set the proper admin now that initialization is done
admin = admin_;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == admin, "BErc20WBTCDelegator::_setImplementation: Caller must be admin");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives bTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
redeemTokens; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems bTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
redeemAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
borrowAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
borrower; repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) {
borrower; repayAmount; bTokenCollateral; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) external returns (bool) {
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
spender; amount; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint) {
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint) {
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
owner; // Shh
delegateAndReturn();
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by bController to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block borrow interest rate for this bToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block supply interest rate for this bToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external returns (uint) {
account; // Shh
delegateAndReturn();
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Get cash balance of this bToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Applies accrued interest to total borrows and reserves.
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another bToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) {
liquidator; borrower; seizeTokens; // Shh
delegateAndReturn();
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
newPendingAdmin; // Shh
delegateAndReturn();
}
/**
* @notice Sets a new bController for the market
* @dev Admin function to set a new bController
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBController(BControllerInterface newBController) public returns (uint) {
newBController; // Shh
delegateAndReturn();
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) {
newReserveFactorMantissa; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrues interest and adds reserves by transferring from admin
* @param addAmount Amount of reserves to add
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
addAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external returns (uint) {
reduceAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
newInterestRateModel; // Shh
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"BErc20WBTCDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | contract BErc20WBTCDelegator is BTokenInterface, BErc20Interface, BDelegatorInterface {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param bController_ The address of the BController
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(address underlying_,
BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address implementation_,
bytes memory becomeImplementationData) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)",
underlying_,
bController_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_));
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
// Set the proper admin now that initialization is done
admin = admin_;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == admin, "BErc20WBTCDelegator::_setImplementation: Caller must be admin");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives bTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
redeemTokens; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems bTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
redeemAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
borrowAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
borrower; repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) {
borrower; repayAmount; bTokenCollateral; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) external returns (bool) {
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
spender; amount; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint) {
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint) {
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
owner; // Shh
delegateAndReturn();
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by bController to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block borrow interest rate for this bToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block supply interest rate for this bToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external returns (uint) {
account; // Shh
delegateAndReturn();
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Get cash balance of this bToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Applies accrued interest to total borrows and reserves.
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another bToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) {
liquidator; borrower; seizeTokens; // Shh
delegateAndReturn();
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
newPendingAdmin; // Shh
delegateAndReturn();
}
/**
* @notice Sets a new bController for the market
* @dev Admin function to set a new bController
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBController(BControllerInterface newBController) public returns (uint) {
newBController; // Shh
delegateAndReturn();
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) {
newReserveFactorMantissa; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrues interest and adds reserves by transferring from admin
* @param addAmount Amount of reserves to add
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
addAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external returns (uint) {
reduceAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
newInterestRateModel; // Shh
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"BErc20WBTCDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | 49,331 |
25 | // The contract is in force, accepting payments and/ granting tokens. | Open,
| Open,
| 51,084 |
97 | // How many tokens one gets from a certain amount of ethereum. | function ethereumToTokens_(uint _ethereumAmount)
public
view
returns(uint)
{
require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth.");
if (icoPhase) {
return _ethereumAmount.div(tokenPriceInitial_) * 1e18;
}
| function ethereumToTokens_(uint _ethereumAmount)
public
view
returns(uint)
{
require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth.");
if (icoPhase) {
return _ethereumAmount.div(tokenPriceInitial_) * 1e18;
}
| 52,317 |
1 | // All returned prices calculated with this precision (18 decimals) | uint256 private constant PRECISION = 10**DECIMALS; //1e18 == $1
uint256 public constant DECIMALS = 18;
uint256 private constant USDC_RAW_PRICE = 1e6;
uint256 private constant USDT_RAW_PRICE = 1e6;
| uint256 private constant PRECISION = 10**DECIMALS; //1e18 == $1
uint256 public constant DECIMALS = 18;
uint256 private constant USDC_RAW_PRICE = 1e6;
uint256 private constant USDT_RAW_PRICE = 1e6;
| 19,472 |
29 | // reset state back to Initial Reporter | IInitialReporter _initialParticipant = getInitialReporter();
delete participants;
participants.push(_initialParticipant);
_initialParticipant.resetReportTimestamp();
| IInitialReporter _initialParticipant = getInitialReporter();
delete participants;
participants.push(_initialParticipant);
_initialParticipant.resetReportTimestamp();
| 32,510 |
39 | // Updates the beneficiary params of a community_community address of the community _originalClaimAmountmaximum base amount to be claim by the beneficiary _maxTotalClaim limit that a beneficiary can claimin total _decreaseStep value decreased from maxTotalClaim each time a is beneficiary added _baseInterval base interval to start claiming _incrementInterval increment interval used in each claim _maxBeneficiaries maximum number of beneficiaries / | function updateBeneficiaryParams(
ICommunity _community,
uint256 _originalClaimAmount,
uint256 _maxTotalClaim,
uint256 _decreaseStep,
uint256 _baseInterval,
uint256 _incrementInterval,
uint256 _maxBeneficiaries
| function updateBeneficiaryParams(
ICommunity _community,
uint256 _originalClaimAmount,
uint256 _maxTotalClaim,
uint256 _decreaseStep,
uint256 _baseInterval,
uint256 _incrementInterval,
uint256 _maxBeneficiaries
| 23,919 |
47 | // Returns number of deposits for the given address. Allows iteration over deposits.See getDeposit_user an address to query deposit length forreturn number of deposits for the given address / | function getDepositsLength(address _user) external view returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
| function getDepositsLength(address _user) external view returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
| 46,932 |
30 | // ВЬЮГА->[ВЬЮ]-ГА^^^ | syllab_rule SYLLABER_16 language=Russian
| syllab_rule SYLLABER_16 language=Russian
| 40,417 |
353 | // Checks if a specific token is controlled by the Prize Pool/controlledToken The address of the token to check/ return True if the token is a controlled token, false otherwise | function _isControlled(address controlledToken) internal view returns (bool) {
return _tokens.contains(controlledToken);
}
| function _isControlled(address controlledToken) internal view returns (bool) {
return _tokens.contains(controlledToken);
}
| 54,872 |
25 | // Lock | uint constant public operVestingSupply = 30000000 * E18;
uint constant public operVestingLockDate = 3 * month;
uint constant public operVestingTime = 24;
uint constant public mktVestingSupply = 30000000 * E18;
uint constant public mktVestingLockDate = 2 * month;
uint constant public mktVestingTime = 18;
uint constant public bDevVestingSupply = 37500000 * E18;
uint constant public bDevVestingLockDate = 3 * month;
| uint constant public operVestingSupply = 30000000 * E18;
uint constant public operVestingLockDate = 3 * month;
uint constant public operVestingTime = 24;
uint constant public mktVestingSupply = 30000000 * E18;
uint constant public mktVestingLockDate = 2 * month;
uint constant public mktVestingTime = 18;
uint constant public bDevVestingSupply = 37500000 * E18;
uint constant public bDevVestingLockDate = 3 * month;
| 41,922 |
4 | // Ensures tx is included in block no after deadline. | modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "DEADLINE EXPIRED");
_;
}
| modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "DEADLINE EXPIRED");
_;
}
| 51,125 |
3 | // uint256 private _jewelFinalPaymentAmountETH = 3.16 ether;~5000 EUR = ~3.16 ETH (1 EUR ~= 0.00063 ETH) | uint256 private _jewelFinalPaymentAmountETH = 0.003 ether; // only for testing purposes
| uint256 private _jewelFinalPaymentAmountETH = 0.003 ether; // only for testing purposes
| 26,125 |
4 | // stake - amount of ether staked for this relay/unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'/withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called/owner - address that receives revenue and manages relayManager's stake | struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawBlock;
address payable owner;
}
| struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawBlock;
address payable owner;
}
| 21,738 |
5 | // Gets the approved address for a token ID, or zero if no address set_tokenId uint256 ID of the token to query the approval of return address currently approved for the given token ID/ | function getApproved(uint256 _tokenId) public view returns (address) {
return address(0);
}
| function getApproved(uint256 _tokenId) public view returns (address) {
return address(0);
}
| 46,980 |
71 | // may need to be computed due to EVM rounding errors | uint256 computedValue;
if(!self.isCanceled){
if(self.totalValuation == self.currentBucket){
| uint256 computedValue;
if(!self.isCanceled){
if(self.totalValuation == self.currentBucket){
| 13,354 |
66 | // Helper to decode rule arguments | function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
| function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
| 18,331 |
54 | // Internal function to burn the tokens from an account after expiration. account Address of the account. / | function _clear(address account) internal {
require(!_notExpired(), "ACOToken::_clear: Token not expired yet");
require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method");
_callBurn(account, balanceOf(account));
}
| function _clear(address account) internal {
require(!_notExpired(), "ACOToken::_clear: Token not expired yet");
require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method");
_callBurn(account, balanceOf(account));
}
| 14,771 |
46 | // Determine the dDai to redeem using the exchange rate. | dDaiBurned = (daiToReceive.mul(_SCALING_FACTOR)).div(_dDaiExchangeRate);
| dDaiBurned = (daiToReceive.mul(_SCALING_FACTOR)).div(_dDaiExchangeRate);
| 30,750 |
26 | // the version number representing the type of aggregator the proxypoints to. / | function version()
external
view
override
returns (uint256)
| function version()
external
view
override
returns (uint256)
| 53,528 |
317 | // EIP20Gateway ContractEIP20Gateway act as medium to send messages from origin chain toauxiliary chain. Currently gateway supports stake and revert stake message. / | contract EIP20Gateway is GatewayBase {
/* Events */
/** Emitted whenever a stake process is initiated. */
event StakeIntentDeclared(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
address _beneficiary,
uint256 _amount
);
/** Emitted whenever a stake is completed. */
event StakeProgressed(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount,
bool _proofProgress,
bytes32 _unlockSecret
);
/** Emitted whenever a process is initiated to revert stake. */
event RevertStakeIntentDeclared(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount
);
/** Emitted whenever a stake is reverted. */
event StakeReverted(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount
);
/** Emitted whenever a redeem intent is confirmed. */
event RedeemIntentConfirmed(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
address _beneficiary,
uint256 _amount,
uint256 _blockHeight,
bytes32 _hashLock
);
/** Emitted whenever a unstake process is complete. */
event UnstakeProgressed(
bytes32 indexed _messageHash,
address _redeemer,
address _beneficiary,
uint256 _redeemAmount,
uint256 _unstakeAmount,
uint256 _rewardAmount,
bool _proofProgress,
bytes32 _unlockSecret
);
/** Emitted whenever a revert redeem intent is confirmed. */
event RevertRedeemIntentConfirmed(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
uint256 _amount
);
/** Emitted whenever revert redeem is completed. */
event RevertRedeemComplete(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
uint256 _amount
);
/* Struct */
/**
* Stake stores the stake amount, beneficiary address, message data and
* facilitator address.
*/
struct Stake {
/** Amount that will be staked. */
uint256 amount;
/**
* Address where the utility tokens will be minted in the
* auxiliary chain.
*/
address beneficiary;
/** Bounty kept by facilitator for stake message transfer. */
uint256 bounty;
}
/**
* Unstake stores the unstake/redeem information
* like unstake/redeem amount, beneficiary address, message data.
*/
struct Unstake {
/** Amount that will be unstaked. */
uint256 amount;
/** Address that will receive the unstaked token. */
address beneficiary;
}
/* Public Variables */
/** Specifies if the Gateway is activated for any new process. */
bool public activated;
/** Escrow address to lock staked fund. */
SimpleStake public stakeVault;
/** Address of EIP20 token. */
EIP20Interface public token;
/**
* Address of ERC20 token in which the facilitator will stake(bounty)
* for a process.
*/
EIP20Interface public baseToken;
/** Address where token will be burned. */
address public burner;
/** Maps messageHash to the Stake object. */
mapping(bytes32 /*messageHash*/ => Stake) stakes;
/** Maps messageHash to the Unstake object. */
mapping(bytes32 /*messageHash*/ => Unstake) unstakes;
/* Modifiers */
/** Checks that contract is active. */
modifier isActive() {
require(
activated == true,
"Gateway is not activated."
);
_;
}
/* Constructor */
/**
* @notice Initialize the contract by providing the ERC20 token address
* for which the gateway will enable facilitation of stake and
* mint.
*
* @param _token The ERC20 token contract address that will be
* staked and corresponding utility tokens will be minted
* in auxiliary chain.
* @param _baseToken The ERC20 token address that will be used for
* staking bounty from the facilitators.
* @param _stateRootProvider Contract address which implements
* StateRootInterface.
* @param _bounty The amount that facilitator will stakes to initiate the
* stake process.
* @param _organization Address of an organization contract.
* @param _burner Address where tokens will be burned.
*/
constructor(
EIP20Interface _token,
EIP20Interface _baseToken,
StateRootInterface _stateRootProvider,
uint256 _bounty,
OrganizationInterface _organization,
address _burner
)
GatewayBase(
_stateRootProvider,
_bounty,
_organization
)
public
{
require(
address(_token) != address(0),
"Token contract address must not be zero."
);
require(
address(_baseToken) != address(0),
"Base token contract address for bounty must not be zero"
);
token = _token;
baseToken = _baseToken;
burner = _burner;
// gateway is in-active initially.
activated = false;
// deploy simpleStake contract that will keep the staked amounts.
stakeVault = new SimpleStake(_token, address(this));
}
/* External functions */
/**
* @notice Initiates the stake process. In order to stake the staker
* needs to approve Gateway contract for stake amount.
* Staked amount is transferred from staker address to
* Gateway contract. Bounty amount is also transferred from staker.
*
* @param _amount Stake amount that will be transferred from the staker
* account.
* @param _beneficiary The address in the auxiliary chain where the utility
* tokens will be minted.
* @param _gasPrice Gas price that staker is ready to pay to get the stake
* and mint process done.
* @param _gasLimit Gas limit that staker is ready to pay.
* @param _nonce Nonce of the staker address.
* @param _hashLock Hash Lock provided by the facilitator.
*
* @return messageHash_ Message hash is unique for each request.
*/
function stake(
uint256 _amount,
address _beneficiary,
uint256 _gasPrice,
uint256 _gasLimit,
uint256 _nonce,
bytes32 _hashLock
)
external
isActive
returns (bytes32 messageHash_)
{
address staker = msg.sender;
require(
_amount > uint256(0),
"Stake amount must not be zero."
);
require(
_beneficiary != address(0),
"Beneficiary address must not be zero."
);
/*
* Maximum reward possible is _gasPrice * _gasLimit, we check this
* upfront in this function to make sure that after minting of the
* tokens it is possible to give the reward to the facilitator.
*/
require(
_amount > _gasPrice.mul(_gasLimit),
"Maximum possible reward must be less than the stake amount."
);
// Get the stake intent hash.
bytes32 intentHash = GatewayLib.hashStakeIntent(
_amount,
_beneficiary,
address(this)
);
MessageBus.Message memory message = getMessage(
intentHash,
_nonce,
_gasPrice,
_gasLimit,
staker,
_hashLock
);
messageHash_ = storeMessage(message);
registerOutboxProcess(
staker,
_nonce,
messageHash_
);
// New stake object
stakes[messageHash_] = Stake({
amount : _amount,
beneficiary : _beneficiary,
bounty : bounty
});
// Declare message in outbox
MessageBus.declareMessage(
messageBox,
messages[messageHash_]
);
// Transfer staker amount to the gateway.
require(
token.transferFrom(staker, address(this), _amount),
"Stake amount must be transferred to gateway"
);
// Transfer the bounty amount to the gateway.
require(
baseToken.transferFrom(staker, address(this), bounty),
"Bounty amount must be transferred to gateway"
);
emit StakeIntentDeclared(
messageHash_,
staker,
_nonce,
_beneficiary,
_amount
);
}
/**
* @notice Completes the stake process.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _unlockSecret Unlock secret for the hashLock provide by the
* staker while initiating the stake.
*
* @return staker_ Staker address.
* @return stakeAmount_ Stake amount.
*/
function progressStake(
bytes32 _messageHash,
bytes32 _unlockSecret
)
external
returns (
address staker_,
uint256 stakeAmount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero"
);
// Get the message object
MessageBus.Message storage message = messages[_messageHash];
// Progress outbox
MessageBus.progressOutbox(
messageBox,
message,
_unlockSecret
);
(staker_, stakeAmount_) = progressStakeInternal(
_messageHash,
message,
_unlockSecret,
false
);
}
/**
* @notice Completes the stake process by providing the merkle proof
* instead of unlockSecret. In case the facilitator process is not
* able to complete the stake and mint process then this is an
* alternative approach to complete the process
*
* @dev This can be called to prove that the inbox status of messageBox on
* CoGateway is either declared or progressed.
*
* @param _messageHash Message hash.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox outbox of CoGateway.
* @param _blockHeight Block number for which the proof is valid.
* @param _messageStatus Message status i.e. Declared or Progressed that
* will be proved.
*
* @return staker_ Staker address
* @return stakeAmount_ Stake amount
*/
function progressStakeWithProof(
bytes32 _messageHash,
bytes calldata _rlpParentNodes,
uint256 _blockHeight,
uint256 _messageStatus
)
external
returns (
address staker_,
uint256 stakeAmount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP encoded parent nodes must not be zero."
);
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Get the message object
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressOutboxWithProof(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot,
MessageBus.MessageStatus(_messageStatus)
);
(staker_, stakeAmount_) = progressStakeInternal(
_messageHash,
message,
bytes32(0),
true
);
}
/**
* @notice Revert stake process and get the stake
* amount back. Only staker can revert stake by providing
* penalty i.e. 1.5 times of bounty amount. On progress revert stake
* penalty and facilitator bounty will be burned.
*
* @param _messageHash Message hash.
*
* @return staker_ Staker address
* @return stakerNonce_ Staker nonce
* @return amount_ Stake amount
*/
function revertStake(
bytes32 _messageHash
)
external
returns (
address staker_,
uint256 stakerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
MessageBus.Message storage message = messages[_messageHash];
require(
message.sender == msg.sender,
"Only staker can revert stake."
);
// Declare stake revocation.
MessageBus.declareRevocationMessage(
messageBox,
message
);
staker_ = message.sender;
stakerNonce_ = message.nonce;
amount_ = stakes[_messageHash].amount;
// Penalty charged to staker for revert stake.
uint256 penalty = penaltyFromBounty(stakes[_messageHash].bounty);
// Transfer the penalty amount to burner.
require(
baseToken.transferFrom(msg.sender, burner, penalty),
"Staker must approve gateway for penalty amount."
);
emit RevertStakeIntentDeclared(
_messageHash,
staker_,
stakerNonce_,
amount_
);
}
/**
* @notice Complete revert stake by providing the merkle proof.
* This method will return stake amount to staker and burn
* facilitator bounty.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _blockHeight Block number for which the proof is valid
* @param _rlpParentNodes RLP encoded parent node data to prove
* DeclaredRevocation in messageBox inbox of
* CoGateway.
*
* @return staker_ Staker address.
* @return stakerNonce_ Staker nonce.
* @return amount_ Stake amount.
*/
function progressRevertStake(
bytes32 _messageHash,
uint256 _blockHeight,
bytes calldata _rlpParentNodes
)
external
returns (
address staker_,
uint256 stakerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero."
);
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
require(
message.intentHash != bytes32(0),
"StakeIntentHash must not be zero."
);
// Get the storageRoot for the given block height.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
amount_ = stakes[_messageHash].amount;
require(
amount_ > 0,
"Stake request must exist."
);
staker_ = message.sender;
stakerNonce_ = message.nonce;
uint256 stakeBounty = stakes[_messageHash].bounty;
// Progress with revocation message.
MessageBus.progressOutboxRevocation(
messageBox,
message,
MESSAGE_BOX_OFFSET,
_rlpParentNodes,
storageRoot,
MessageBus.MessageStatus.Revoked
);
delete stakes[_messageHash];
// Transfer the staked amount to the staker.
token.transfer(message.sender, amount_);
// Burn facilitator bounty.
baseToken.transfer(burner, stakeBounty);
emit StakeReverted(
_messageHash,
staker_,
stakerNonce_,
amount_
);
}
/**
* @notice Declare redeem intent.
*
* @param _redeemer Redeemer address.
* @param _redeemerNonce Redeemer nonce.
* @param _beneficiary Address where the redeemed tokens will be
* transferred.
* @param _amount Redeem amount.
* @param _gasPrice Gas price that redeemer is ready to pay to get the
* redeem and unstake process done.
* @param _gasLimit Gas limit that redeemer is ready to pay.
* @param _blockHeight Block number for which the proof is valid.
* @param _hashLock Hash lock.
* @param _rlpParentNodes RLP encoded parent node data to prove
* Declared in messageBox outbox of
* CoGateway.
*
* @return messageHash_ Message hash.
*/
function confirmRedeemIntent(
address _redeemer,
uint256 _redeemerNonce,
address _beneficiary,
uint256 _amount,
uint256 _gasPrice,
uint256 _gasLimit,
uint256 _blockHeight,
bytes32 _hashLock,
bytes calldata _rlpParentNodes
)
external
returns (bytes32 messageHash_)
{
// Get the initial gas.
uint256 initialGas = gasleft();
require(
_redeemer != address(0),
"Redeemer address must not be zero."
);
require(
_beneficiary != address(0),
"Beneficiary address must not be zero."
);
require(
_amount != 0,
"Redeem amount must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP encoded parent nodes must not be zero."
);
/*
* Maximum reward possible is _gasPrice * _gasLimit, we check this
* upfront in this function to make sure that after unstake of the
* tokens it is possible to give the reward to the facilitator.
*/
require(
_amount > _gasPrice.mul(_gasLimit),
"Maximum possible reward must be less than the redeem amount."
);
bytes32 intentHash = hashRedeemIntent(
_amount,
_beneficiary
);
MessageBus.Message memory message = MessageBus.Message(
intentHash,
_redeemerNonce,
_gasPrice,
_gasLimit,
_redeemer,
_hashLock,
0 // Gas consumed will be updated at the end of this function.
);
messageHash_ = storeMessage(message);
registerInboxProcess(
message.sender,
message.nonce,
messageHash_
);
unstakes[messageHash_] = Unstake({
amount : _amount,
beneficiary : _beneficiary
});
confirmRedeemIntentInternal(
messages[messageHash_],
_blockHeight,
_rlpParentNodes
);
// Emit RedeemIntentConfirmed event.
emit RedeemIntentConfirmed(
messageHash_,
_redeemer,
_redeemerNonce,
_beneficiary,
_amount,
_blockHeight,
_hashLock
);
// Update the gas consumed for this function.
messages[messageHash_].gasConsumed = initialGas.sub(gasleft());
}
/**
* @notice Complete unstake.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _unlockSecret Unlock secret for the hashLock provide by the
* facilitator while initiating the redeem.
*
* @return redeemer_ Redeemer address.
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator.
*/
function progressUnstake(
bytes32 _messageHash,
bytes32 _unlockSecret
)
external
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
// Get the inital gas.
uint256 initialGas = gasleft();
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressInbox(
messageBox,
message,
_unlockSecret
);
(redeemAmount_, unstakeAmount_, rewardAmount_) =
progressUnstakeInternal(_messageHash, initialGas, _unlockSecret, false);
}
/**
* @notice Gets the penalty amount. If the message hash does not exist in
* stakes mapping it will return zero amount. If the message is
* already progressed or revoked then the penalty amount will be
* zero.
*
* @param _messageHash Message hash.
*
* @return penalty_ Penalty amount.
*/
function penalty(bytes32 _messageHash)
external
view
returns (uint256 penalty_)
{
penalty_ = super.penaltyFromBounty(stakes[_messageHash].bounty);
}
/**
* @notice Completes the redeem process by providing the merkle proof
* instead of unlockSecret. In case the facilitator process is not
* able to complete the redeem and unstake process then this is an
* alternative approach to complete the process
*
* @dev This can be called to prove that the outbox status of messageBox on
* CoGateway is either declared or progressed.
*
* @param _messageHash Message hash.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox inbox of CoGateway.
* @param _blockHeight Block number for which the proof is valid.
* @param _messageStatus Message status i.e. Declared or Progressed that
* will be proved.
*
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator.
*/
function progressUnstakeWithProof(
bytes32 _messageHash,
bytes calldata _rlpParentNodes,
uint256 _blockHeight,
uint256 _messageStatus
)
external
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
// Get the initial gas.
uint256 initialGas = gasleft();
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero"
);
// Get the storage root for the given block height.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero"
);
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressInboxWithProof(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot,
MessageBus.MessageStatus(_messageStatus)
);
(redeemAmount_, unstakeAmount_, rewardAmount_) =
progressUnstakeInternal(_messageHash, initialGas, bytes32(0), true);
}
/**
* @notice Declare redeem revert intent.
* This will set message status to revoked. This method will also
* clear unstakes mapping storage.
*
* @param _messageHash Message hash.
* @param _blockHeight Block number for which the proof is valid.
* @param _rlpParentNodes RLP encoded parent node data to prove
* DeclaredRevocation in messageBox outbox of
* CoGateway.
*
* @return redeemer_ Redeemer address.
* @return redeemerNonce_ Redeemer nonce.
* @return amount_ Redeem amount.
*/
function confirmRevertRedeemIntent(
bytes32 _messageHash,
uint256 _blockHeight,
bytes calldata _rlpParentNodes
)
external
returns (
address redeemer_,
uint256 redeemerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero."
);
amount_ = unstakes[_messageHash].amount;
require(
amount_ > uint256(0),
"Unstake amount must not be zero."
);
delete unstakes[_messageHash];
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
require(
message.intentHash != bytes32(0),
"RevertRedeem intent hash must not be zero."
);
// Get the storage root
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Confirm revocation
MessageBus.confirmRevocation(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot
);
redeemer_ = message.sender;
redeemerNonce_ = message.nonce;
emit RevertRedeemIntentConfirmed(
_messageHash,
redeemer_,
redeemerNonce_,
amount_
);
}
/**
* @notice Activate Gateway contract. Can be set only by the
* Organization address only once by passing co-gateway address.
*
* @param _coGatewayAddress Address of cogateway.
*
* @return success_ `true` if value is set
*/
function activateGateway(
address _coGatewayAddress
)
external
onlyOrganization
returns (bool success_)
{
require(
_coGatewayAddress != address(0),
"Co-gateway address must not be zero."
);
require(
remoteGateway == address(0),
"Gateway was already activated once."
);
remoteGateway = _coGatewayAddress;
// update the encodedGatewayPath
encodedGatewayPath = BytesLib.bytes32ToBytes(
keccak256(abi.encodePacked(remoteGateway))
);
activated = true;
success_ = true;
}
/**
* @notice Deactivate Gateway contract. Can be set only by the
* organization address
*
* @return success_ `true` if value is set
*/
function deactivateGateway()
external
onlyOrganization
returns (bool success_)
{
require(
activated == true,
"Gateway is already deactivated."
);
activated = false;
success_ = true;
}
/* Private functions */
/**
* @notice Private function to execute confirm redeem intent.
*
* @dev This function is to avoid stack too deep error in
* confirmRedeemIntent function.
*
* @param _message Message object.
* @param _blockHeight Block number for which the proof is valid.
* @param _rlpParentNodes RLP encoded parent nodes.
*
* @return `true` if executed successfully.
*/
function confirmRedeemIntentInternal(
MessageBus.Message storage _message,
uint256 _blockHeight,
bytes memory _rlpParentNodes
)
private
returns (bool)
{
// Get storage root.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Confirm message.
MessageBus.confirmMessage(
messageBox,
_message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot
);
return true;
}
/**
* @notice Private function contains logic for process stake.
*
* @param _messageHash Message hash.
* @param _message Message object.
* @param _unlockSecret For process with hash lock, proofProgress event
* param is set to false otherwise set to true.
*
* @return staker_ Staker address
* @return stakeAmount_ Stake amount
*/
function progressStakeInternal(
bytes32 _messageHash,
MessageBus.Message storage _message,
bytes32 _unlockSecret,
bool _proofProgress
)
private
returns (
address staker_,
uint256 stakeAmount_
)
{
// Get the staker address
staker_ = _message.sender;
// Get the stake amount.
stakeAmount_ = stakes[_messageHash].amount;
require(
stakeAmount_ > 0,
"Stake request must exist."
);
uint256 stakedBounty = stakes[_messageHash].bounty;
delete stakes[_messageHash];
// Transfer the staked amount to stakeVault.
token.transfer(address(stakeVault), stakeAmount_);
baseToken.transfer(msg.sender, stakedBounty);
emit StakeProgressed(
_messageHash,
staker_,
_message.nonce,
stakeAmount_,
_proofProgress,
_unlockSecret
);
}
/**
* @notice This is internal method for process unstake called from external
* methods which processUnstake(with hashlock) and
* processUnstakeWithProof
*
* @param _messageHash hash to identify message
* @param _initialGas initial available gas during process unstake call.
* @param _unlockSecret Block number for which the proof is valid
* @param _proofProgress true if progress with proof and false if
* progress with unlock secret.
*
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator
*/
function progressUnstakeInternal(
bytes32 _messageHash,
uint256 _initialGas,
bytes32 _unlockSecret,
bool _proofProgress
)
private
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
Unstake storage unStake = unstakes[_messageHash];
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
redeemAmount_ = unStake.amount;
require(
redeemAmount_ > 0,
"Unstake request must exist."
);
/*
* Reward calculation depends upon
* - the gas consumed in target chain for confirmation and progress steps.
* - gas price and gas limit provided in the message.
*/
(rewardAmount_, message.gasConsumed) = feeAmount(
message.gasConsumed,
message.gasLimit,
message.gasPrice,
_initialGas
);
unstakeAmount_ = redeemAmount_.sub(rewardAmount_);
address beneficiary = unstakes[_messageHash].beneficiary;
delete unstakes[_messageHash];
// Release the amount to beneficiary, but with reward subtracted.
stakeVault.releaseTo(beneficiary, unstakeAmount_);
// Reward facilitator with the reward amount.
stakeVault.releaseTo(msg.sender, rewardAmount_);
emit UnstakeProgressed(
_messageHash,
message.sender,
beneficiary,
redeemAmount_,
unstakeAmount_,
rewardAmount_,
_proofProgress,
_unlockSecret
);
}
/**
* @notice Private function to calculate redeem intent hash.
*
* @dev This function is to avoid stack too deep error in
* confirmRedeemIntent function.
*
* @param _amount Redeem amount.
* @param _beneficiary Unstake account.
*
* @return bytes32 Redeem intent hash.
*/
function hashRedeemIntent(
uint256 _amount,
address _beneficiary
)
private
view
returns(bytes32)
{
return GatewayLib.hashRedeemIntent(
_amount,
_beneficiary,
remoteGateway
);
}
} | contract EIP20Gateway is GatewayBase {
/* Events */
/** Emitted whenever a stake process is initiated. */
event StakeIntentDeclared(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
address _beneficiary,
uint256 _amount
);
/** Emitted whenever a stake is completed. */
event StakeProgressed(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount,
bool _proofProgress,
bytes32 _unlockSecret
);
/** Emitted whenever a process is initiated to revert stake. */
event RevertStakeIntentDeclared(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount
);
/** Emitted whenever a stake is reverted. */
event StakeReverted(
bytes32 indexed _messageHash,
address _staker,
uint256 _stakerNonce,
uint256 _amount
);
/** Emitted whenever a redeem intent is confirmed. */
event RedeemIntentConfirmed(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
address _beneficiary,
uint256 _amount,
uint256 _blockHeight,
bytes32 _hashLock
);
/** Emitted whenever a unstake process is complete. */
event UnstakeProgressed(
bytes32 indexed _messageHash,
address _redeemer,
address _beneficiary,
uint256 _redeemAmount,
uint256 _unstakeAmount,
uint256 _rewardAmount,
bool _proofProgress,
bytes32 _unlockSecret
);
/** Emitted whenever a revert redeem intent is confirmed. */
event RevertRedeemIntentConfirmed(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
uint256 _amount
);
/** Emitted whenever revert redeem is completed. */
event RevertRedeemComplete(
bytes32 indexed _messageHash,
address _redeemer,
uint256 _redeemerNonce,
uint256 _amount
);
/* Struct */
/**
* Stake stores the stake amount, beneficiary address, message data and
* facilitator address.
*/
struct Stake {
/** Amount that will be staked. */
uint256 amount;
/**
* Address where the utility tokens will be minted in the
* auxiliary chain.
*/
address beneficiary;
/** Bounty kept by facilitator for stake message transfer. */
uint256 bounty;
}
/**
* Unstake stores the unstake/redeem information
* like unstake/redeem amount, beneficiary address, message data.
*/
struct Unstake {
/** Amount that will be unstaked. */
uint256 amount;
/** Address that will receive the unstaked token. */
address beneficiary;
}
/* Public Variables */
/** Specifies if the Gateway is activated for any new process. */
bool public activated;
/** Escrow address to lock staked fund. */
SimpleStake public stakeVault;
/** Address of EIP20 token. */
EIP20Interface public token;
/**
* Address of ERC20 token in which the facilitator will stake(bounty)
* for a process.
*/
EIP20Interface public baseToken;
/** Address where token will be burned. */
address public burner;
/** Maps messageHash to the Stake object. */
mapping(bytes32 /*messageHash*/ => Stake) stakes;
/** Maps messageHash to the Unstake object. */
mapping(bytes32 /*messageHash*/ => Unstake) unstakes;
/* Modifiers */
/** Checks that contract is active. */
modifier isActive() {
require(
activated == true,
"Gateway is not activated."
);
_;
}
/* Constructor */
/**
* @notice Initialize the contract by providing the ERC20 token address
* for which the gateway will enable facilitation of stake and
* mint.
*
* @param _token The ERC20 token contract address that will be
* staked and corresponding utility tokens will be minted
* in auxiliary chain.
* @param _baseToken The ERC20 token address that will be used for
* staking bounty from the facilitators.
* @param _stateRootProvider Contract address which implements
* StateRootInterface.
* @param _bounty The amount that facilitator will stakes to initiate the
* stake process.
* @param _organization Address of an organization contract.
* @param _burner Address where tokens will be burned.
*/
constructor(
EIP20Interface _token,
EIP20Interface _baseToken,
StateRootInterface _stateRootProvider,
uint256 _bounty,
OrganizationInterface _organization,
address _burner
)
GatewayBase(
_stateRootProvider,
_bounty,
_organization
)
public
{
require(
address(_token) != address(0),
"Token contract address must not be zero."
);
require(
address(_baseToken) != address(0),
"Base token contract address for bounty must not be zero"
);
token = _token;
baseToken = _baseToken;
burner = _burner;
// gateway is in-active initially.
activated = false;
// deploy simpleStake contract that will keep the staked amounts.
stakeVault = new SimpleStake(_token, address(this));
}
/* External functions */
/**
* @notice Initiates the stake process. In order to stake the staker
* needs to approve Gateway contract for stake amount.
* Staked amount is transferred from staker address to
* Gateway contract. Bounty amount is also transferred from staker.
*
* @param _amount Stake amount that will be transferred from the staker
* account.
* @param _beneficiary The address in the auxiliary chain where the utility
* tokens will be minted.
* @param _gasPrice Gas price that staker is ready to pay to get the stake
* and mint process done.
* @param _gasLimit Gas limit that staker is ready to pay.
* @param _nonce Nonce of the staker address.
* @param _hashLock Hash Lock provided by the facilitator.
*
* @return messageHash_ Message hash is unique for each request.
*/
function stake(
uint256 _amount,
address _beneficiary,
uint256 _gasPrice,
uint256 _gasLimit,
uint256 _nonce,
bytes32 _hashLock
)
external
isActive
returns (bytes32 messageHash_)
{
address staker = msg.sender;
require(
_amount > uint256(0),
"Stake amount must not be zero."
);
require(
_beneficiary != address(0),
"Beneficiary address must not be zero."
);
/*
* Maximum reward possible is _gasPrice * _gasLimit, we check this
* upfront in this function to make sure that after minting of the
* tokens it is possible to give the reward to the facilitator.
*/
require(
_amount > _gasPrice.mul(_gasLimit),
"Maximum possible reward must be less than the stake amount."
);
// Get the stake intent hash.
bytes32 intentHash = GatewayLib.hashStakeIntent(
_amount,
_beneficiary,
address(this)
);
MessageBus.Message memory message = getMessage(
intentHash,
_nonce,
_gasPrice,
_gasLimit,
staker,
_hashLock
);
messageHash_ = storeMessage(message);
registerOutboxProcess(
staker,
_nonce,
messageHash_
);
// New stake object
stakes[messageHash_] = Stake({
amount : _amount,
beneficiary : _beneficiary,
bounty : bounty
});
// Declare message in outbox
MessageBus.declareMessage(
messageBox,
messages[messageHash_]
);
// Transfer staker amount to the gateway.
require(
token.transferFrom(staker, address(this), _amount),
"Stake amount must be transferred to gateway"
);
// Transfer the bounty amount to the gateway.
require(
baseToken.transferFrom(staker, address(this), bounty),
"Bounty amount must be transferred to gateway"
);
emit StakeIntentDeclared(
messageHash_,
staker,
_nonce,
_beneficiary,
_amount
);
}
/**
* @notice Completes the stake process.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _unlockSecret Unlock secret for the hashLock provide by the
* staker while initiating the stake.
*
* @return staker_ Staker address.
* @return stakeAmount_ Stake amount.
*/
function progressStake(
bytes32 _messageHash,
bytes32 _unlockSecret
)
external
returns (
address staker_,
uint256 stakeAmount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero"
);
// Get the message object
MessageBus.Message storage message = messages[_messageHash];
// Progress outbox
MessageBus.progressOutbox(
messageBox,
message,
_unlockSecret
);
(staker_, stakeAmount_) = progressStakeInternal(
_messageHash,
message,
_unlockSecret,
false
);
}
/**
* @notice Completes the stake process by providing the merkle proof
* instead of unlockSecret. In case the facilitator process is not
* able to complete the stake and mint process then this is an
* alternative approach to complete the process
*
* @dev This can be called to prove that the inbox status of messageBox on
* CoGateway is either declared or progressed.
*
* @param _messageHash Message hash.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox outbox of CoGateway.
* @param _blockHeight Block number for which the proof is valid.
* @param _messageStatus Message status i.e. Declared or Progressed that
* will be proved.
*
* @return staker_ Staker address
* @return stakeAmount_ Stake amount
*/
function progressStakeWithProof(
bytes32 _messageHash,
bytes calldata _rlpParentNodes,
uint256 _blockHeight,
uint256 _messageStatus
)
external
returns (
address staker_,
uint256 stakeAmount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP encoded parent nodes must not be zero."
);
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Get the message object
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressOutboxWithProof(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot,
MessageBus.MessageStatus(_messageStatus)
);
(staker_, stakeAmount_) = progressStakeInternal(
_messageHash,
message,
bytes32(0),
true
);
}
/**
* @notice Revert stake process and get the stake
* amount back. Only staker can revert stake by providing
* penalty i.e. 1.5 times of bounty amount. On progress revert stake
* penalty and facilitator bounty will be burned.
*
* @param _messageHash Message hash.
*
* @return staker_ Staker address
* @return stakerNonce_ Staker nonce
* @return amount_ Stake amount
*/
function revertStake(
bytes32 _messageHash
)
external
returns (
address staker_,
uint256 stakerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
MessageBus.Message storage message = messages[_messageHash];
require(
message.sender == msg.sender,
"Only staker can revert stake."
);
// Declare stake revocation.
MessageBus.declareRevocationMessage(
messageBox,
message
);
staker_ = message.sender;
stakerNonce_ = message.nonce;
amount_ = stakes[_messageHash].amount;
// Penalty charged to staker for revert stake.
uint256 penalty = penaltyFromBounty(stakes[_messageHash].bounty);
// Transfer the penalty amount to burner.
require(
baseToken.transferFrom(msg.sender, burner, penalty),
"Staker must approve gateway for penalty amount."
);
emit RevertStakeIntentDeclared(
_messageHash,
staker_,
stakerNonce_,
amount_
);
}
/**
* @notice Complete revert stake by providing the merkle proof.
* This method will return stake amount to staker and burn
* facilitator bounty.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _blockHeight Block number for which the proof is valid
* @param _rlpParentNodes RLP encoded parent node data to prove
* DeclaredRevocation in messageBox inbox of
* CoGateway.
*
* @return staker_ Staker address.
* @return stakerNonce_ Staker nonce.
* @return amount_ Stake amount.
*/
function progressRevertStake(
bytes32 _messageHash,
uint256 _blockHeight,
bytes calldata _rlpParentNodes
)
external
returns (
address staker_,
uint256 stakerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero."
);
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
require(
message.intentHash != bytes32(0),
"StakeIntentHash must not be zero."
);
// Get the storageRoot for the given block height.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
amount_ = stakes[_messageHash].amount;
require(
amount_ > 0,
"Stake request must exist."
);
staker_ = message.sender;
stakerNonce_ = message.nonce;
uint256 stakeBounty = stakes[_messageHash].bounty;
// Progress with revocation message.
MessageBus.progressOutboxRevocation(
messageBox,
message,
MESSAGE_BOX_OFFSET,
_rlpParentNodes,
storageRoot,
MessageBus.MessageStatus.Revoked
);
delete stakes[_messageHash];
// Transfer the staked amount to the staker.
token.transfer(message.sender, amount_);
// Burn facilitator bounty.
baseToken.transfer(burner, stakeBounty);
emit StakeReverted(
_messageHash,
staker_,
stakerNonce_,
amount_
);
}
/**
* @notice Declare redeem intent.
*
* @param _redeemer Redeemer address.
* @param _redeemerNonce Redeemer nonce.
* @param _beneficiary Address where the redeemed tokens will be
* transferred.
* @param _amount Redeem amount.
* @param _gasPrice Gas price that redeemer is ready to pay to get the
* redeem and unstake process done.
* @param _gasLimit Gas limit that redeemer is ready to pay.
* @param _blockHeight Block number for which the proof is valid.
* @param _hashLock Hash lock.
* @param _rlpParentNodes RLP encoded parent node data to prove
* Declared in messageBox outbox of
* CoGateway.
*
* @return messageHash_ Message hash.
*/
function confirmRedeemIntent(
address _redeemer,
uint256 _redeemerNonce,
address _beneficiary,
uint256 _amount,
uint256 _gasPrice,
uint256 _gasLimit,
uint256 _blockHeight,
bytes32 _hashLock,
bytes calldata _rlpParentNodes
)
external
returns (bytes32 messageHash_)
{
// Get the initial gas.
uint256 initialGas = gasleft();
require(
_redeemer != address(0),
"Redeemer address must not be zero."
);
require(
_beneficiary != address(0),
"Beneficiary address must not be zero."
);
require(
_amount != 0,
"Redeem amount must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP encoded parent nodes must not be zero."
);
/*
* Maximum reward possible is _gasPrice * _gasLimit, we check this
* upfront in this function to make sure that after unstake of the
* tokens it is possible to give the reward to the facilitator.
*/
require(
_amount > _gasPrice.mul(_gasLimit),
"Maximum possible reward must be less than the redeem amount."
);
bytes32 intentHash = hashRedeemIntent(
_amount,
_beneficiary
);
MessageBus.Message memory message = MessageBus.Message(
intentHash,
_redeemerNonce,
_gasPrice,
_gasLimit,
_redeemer,
_hashLock,
0 // Gas consumed will be updated at the end of this function.
);
messageHash_ = storeMessage(message);
registerInboxProcess(
message.sender,
message.nonce,
messageHash_
);
unstakes[messageHash_] = Unstake({
amount : _amount,
beneficiary : _beneficiary
});
confirmRedeemIntentInternal(
messages[messageHash_],
_blockHeight,
_rlpParentNodes
);
// Emit RedeemIntentConfirmed event.
emit RedeemIntentConfirmed(
messageHash_,
_redeemer,
_redeemerNonce,
_beneficiary,
_amount,
_blockHeight,
_hashLock
);
// Update the gas consumed for this function.
messages[messageHash_].gasConsumed = initialGas.sub(gasleft());
}
/**
* @notice Complete unstake.
*
* @dev Message bus ensures correct execution sequence of methods and also
* provides safety mechanism for any possible re-entrancy attack.
*
* @param _messageHash Message hash.
* @param _unlockSecret Unlock secret for the hashLock provide by the
* facilitator while initiating the redeem.
*
* @return redeemer_ Redeemer address.
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator.
*/
function progressUnstake(
bytes32 _messageHash,
bytes32 _unlockSecret
)
external
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
// Get the inital gas.
uint256 initialGas = gasleft();
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressInbox(
messageBox,
message,
_unlockSecret
);
(redeemAmount_, unstakeAmount_, rewardAmount_) =
progressUnstakeInternal(_messageHash, initialGas, _unlockSecret, false);
}
/**
* @notice Gets the penalty amount. If the message hash does not exist in
* stakes mapping it will return zero amount. If the message is
* already progressed or revoked then the penalty amount will be
* zero.
*
* @param _messageHash Message hash.
*
* @return penalty_ Penalty amount.
*/
function penalty(bytes32 _messageHash)
external
view
returns (uint256 penalty_)
{
penalty_ = super.penaltyFromBounty(stakes[_messageHash].bounty);
}
/**
* @notice Completes the redeem process by providing the merkle proof
* instead of unlockSecret. In case the facilitator process is not
* able to complete the redeem and unstake process then this is an
* alternative approach to complete the process
*
* @dev This can be called to prove that the outbox status of messageBox on
* CoGateway is either declared or progressed.
*
* @param _messageHash Message hash.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox inbox of CoGateway.
* @param _blockHeight Block number for which the proof is valid.
* @param _messageStatus Message status i.e. Declared or Progressed that
* will be proved.
*
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator.
*/
function progressUnstakeWithProof(
bytes32 _messageHash,
bytes calldata _rlpParentNodes,
uint256 _blockHeight,
uint256 _messageStatus
)
external
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
// Get the initial gas.
uint256 initialGas = gasleft();
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero"
);
// Get the storage root for the given block height.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero"
);
MessageBus.Message storage message = messages[_messageHash];
MessageBus.progressInboxWithProof(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot,
MessageBus.MessageStatus(_messageStatus)
);
(redeemAmount_, unstakeAmount_, rewardAmount_) =
progressUnstakeInternal(_messageHash, initialGas, bytes32(0), true);
}
/**
* @notice Declare redeem revert intent.
* This will set message status to revoked. This method will also
* clear unstakes mapping storage.
*
* @param _messageHash Message hash.
* @param _blockHeight Block number for which the proof is valid.
* @param _rlpParentNodes RLP encoded parent node data to prove
* DeclaredRevocation in messageBox outbox of
* CoGateway.
*
* @return redeemer_ Redeemer address.
* @return redeemerNonce_ Redeemer nonce.
* @return amount_ Redeem amount.
*/
function confirmRevertRedeemIntent(
bytes32 _messageHash,
uint256 _blockHeight,
bytes calldata _rlpParentNodes
)
external
returns (
address redeemer_,
uint256 redeemerNonce_,
uint256 amount_
)
{
require(
_messageHash != bytes32(0),
"Message hash must not be zero."
);
require(
_rlpParentNodes.length > 0,
"RLP parent nodes must not be zero."
);
amount_ = unstakes[_messageHash].amount;
require(
amount_ > uint256(0),
"Unstake amount must not be zero."
);
delete unstakes[_messageHash];
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
require(
message.intentHash != bytes32(0),
"RevertRedeem intent hash must not be zero."
);
// Get the storage root
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Confirm revocation
MessageBus.confirmRevocation(
messageBox,
message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot
);
redeemer_ = message.sender;
redeemerNonce_ = message.nonce;
emit RevertRedeemIntentConfirmed(
_messageHash,
redeemer_,
redeemerNonce_,
amount_
);
}
/**
* @notice Activate Gateway contract. Can be set only by the
* Organization address only once by passing co-gateway address.
*
* @param _coGatewayAddress Address of cogateway.
*
* @return success_ `true` if value is set
*/
function activateGateway(
address _coGatewayAddress
)
external
onlyOrganization
returns (bool success_)
{
require(
_coGatewayAddress != address(0),
"Co-gateway address must not be zero."
);
require(
remoteGateway == address(0),
"Gateway was already activated once."
);
remoteGateway = _coGatewayAddress;
// update the encodedGatewayPath
encodedGatewayPath = BytesLib.bytes32ToBytes(
keccak256(abi.encodePacked(remoteGateway))
);
activated = true;
success_ = true;
}
/**
* @notice Deactivate Gateway contract. Can be set only by the
* organization address
*
* @return success_ `true` if value is set
*/
function deactivateGateway()
external
onlyOrganization
returns (bool success_)
{
require(
activated == true,
"Gateway is already deactivated."
);
activated = false;
success_ = true;
}
/* Private functions */
/**
* @notice Private function to execute confirm redeem intent.
*
* @dev This function is to avoid stack too deep error in
* confirmRedeemIntent function.
*
* @param _message Message object.
* @param _blockHeight Block number for which the proof is valid.
* @param _rlpParentNodes RLP encoded parent nodes.
*
* @return `true` if executed successfully.
*/
function confirmRedeemIntentInternal(
MessageBus.Message storage _message,
uint256 _blockHeight,
bytes memory _rlpParentNodes
)
private
returns (bool)
{
// Get storage root.
bytes32 storageRoot = storageRoots[_blockHeight];
require(
storageRoot != bytes32(0),
"Storage root must not be zero."
);
// Confirm message.
MessageBus.confirmMessage(
messageBox,
_message,
_rlpParentNodes,
MESSAGE_BOX_OFFSET,
storageRoot
);
return true;
}
/**
* @notice Private function contains logic for process stake.
*
* @param _messageHash Message hash.
* @param _message Message object.
* @param _unlockSecret For process with hash lock, proofProgress event
* param is set to false otherwise set to true.
*
* @return staker_ Staker address
* @return stakeAmount_ Stake amount
*/
function progressStakeInternal(
bytes32 _messageHash,
MessageBus.Message storage _message,
bytes32 _unlockSecret,
bool _proofProgress
)
private
returns (
address staker_,
uint256 stakeAmount_
)
{
// Get the staker address
staker_ = _message.sender;
// Get the stake amount.
stakeAmount_ = stakes[_messageHash].amount;
require(
stakeAmount_ > 0,
"Stake request must exist."
);
uint256 stakedBounty = stakes[_messageHash].bounty;
delete stakes[_messageHash];
// Transfer the staked amount to stakeVault.
token.transfer(address(stakeVault), stakeAmount_);
baseToken.transfer(msg.sender, stakedBounty);
emit StakeProgressed(
_messageHash,
staker_,
_message.nonce,
stakeAmount_,
_proofProgress,
_unlockSecret
);
}
/**
* @notice This is internal method for process unstake called from external
* methods which processUnstake(with hashlock) and
* processUnstakeWithProof
*
* @param _messageHash hash to identify message
* @param _initialGas initial available gas during process unstake call.
* @param _unlockSecret Block number for which the proof is valid
* @param _proofProgress true if progress with proof and false if
* progress with unlock secret.
*
* @return redeemAmount_ Total amount for which the redeem was
* initiated. The reward amount is deducted from the
* total redeem amount and is given to the
* facilitator.
* @return unstakeAmount_ Actual unstake amount, after deducting the reward
* from the total redeem amount.
* @return rewardAmount_ Reward amount that is transferred to facilitator
*/
function progressUnstakeInternal(
bytes32 _messageHash,
uint256 _initialGas,
bytes32 _unlockSecret,
bool _proofProgress
)
private
returns (
uint256 redeemAmount_,
uint256 unstakeAmount_,
uint256 rewardAmount_
)
{
Unstake storage unStake = unstakes[_messageHash];
// Get the message object.
MessageBus.Message storage message = messages[_messageHash];
redeemAmount_ = unStake.amount;
require(
redeemAmount_ > 0,
"Unstake request must exist."
);
/*
* Reward calculation depends upon
* - the gas consumed in target chain for confirmation and progress steps.
* - gas price and gas limit provided in the message.
*/
(rewardAmount_, message.gasConsumed) = feeAmount(
message.gasConsumed,
message.gasLimit,
message.gasPrice,
_initialGas
);
unstakeAmount_ = redeemAmount_.sub(rewardAmount_);
address beneficiary = unstakes[_messageHash].beneficiary;
delete unstakes[_messageHash];
// Release the amount to beneficiary, but with reward subtracted.
stakeVault.releaseTo(beneficiary, unstakeAmount_);
// Reward facilitator with the reward amount.
stakeVault.releaseTo(msg.sender, rewardAmount_);
emit UnstakeProgressed(
_messageHash,
message.sender,
beneficiary,
redeemAmount_,
unstakeAmount_,
rewardAmount_,
_proofProgress,
_unlockSecret
);
}
/**
* @notice Private function to calculate redeem intent hash.
*
* @dev This function is to avoid stack too deep error in
* confirmRedeemIntent function.
*
* @param _amount Redeem amount.
* @param _beneficiary Unstake account.
*
* @return bytes32 Redeem intent hash.
*/
function hashRedeemIntent(
uint256 _amount,
address _beneficiary
)
private
view
returns(bytes32)
{
return GatewayLib.hashRedeemIntent(
_amount,
_beneficiary,
remoteGateway
);
}
} | 28,671 |
177 | // ========== Burns and givebacks ========== / Give USDC profits back. Goes through the minter | function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust {
collateral_token.approve(address(amo_minter), collat_amount);
amo_minter.receiveCollatFromAMO(collat_amount);
}
| function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust {
collateral_token.approve(address(amo_minter), collat_amount);
amo_minter.receiveCollatFromAMO(collat_amount);
}
| 57,721 |
91 | // Returns whether swaps and deposits are currently pausedreturn isPaused Whether swaps and deposits are currently paused / | function paused() external view returns (bool isPaused);
| function paused() external view returns (bool isPaused);
| 36,248 |
184 | // Generation |
string[] private doing = [
"Love Making",
"Fucking",
"Wanking",
"Blowing",
"Nailing",
"Noodling",
"Boning",
"Banging",
|
string[] private doing = [
"Love Making",
"Fucking",
"Wanking",
"Blowing",
"Nailing",
"Noodling",
"Boning",
"Banging",
| 48,266 |
100 | // TestNetaddress private constant uniswapV2Router=0xE592427A0AEce92De3Edee1F18E0157C05861564;MainNet | address private constant uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
| address private constant uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
| 42,561 |
1 | // Allows the initial operator (deployer) to set the operator.Note - crvDepositor has no way to change this back, so it's effectively immutable / | function setOperator(address _operator) external {
require(msg.sender == operator, "!auth");
operator = _operator;
}
| function setOperator(address _operator) external {
require(msg.sender == operator, "!auth");
operator = _operator;
}
| 15,840 |
2 | // Set the factory address and allow it to regiser a new market _factory factory address / | function setFactory(address _factory) external override onlyOwner {
require(_factory != address(0), "ERROR: ZERO_ADDRESS");
factory = _factory;
emit FactorySet(_factory);
}
| function setFactory(address _factory) external override onlyOwner {
require(_factory != address(0), "ERROR: ZERO_ADDRESS");
factory = _factory;
emit FactorySet(_factory);
}
| 32,852 |
81 | // Query if a contract implements interface `id`./id the interface identifier, as specified in ERC-165./ return `true` if the contract implements `id`. | function supportsInterface(bytes4 id) external view returns (bool) {
return
id == 0x01ffc9a7 || //ERC165
id == 0xd9b67a26 || // ERC1155
id == 0x80ac58cd || // ERC721
id == 0x5b5e139f || // ERC721 metadata
id == 0x0e89341c; // ERC1155 metadata
}
| function supportsInterface(bytes4 id) external view returns (bool) {
return
id == 0x01ffc9a7 || //ERC165
id == 0xd9b67a26 || // ERC1155
id == 0x80ac58cd || // ERC721
id == 0x5b5e139f || // ERC721 metadata
id == 0x0e89341c; // ERC1155 metadata
}
| 71,322 |
40 | // Calculates the annual rate for a given reward rate and specific interval/_rateMantissa The reward rate as a mantissa between [0, 1e18]/_timeDelta The interval in seconds/ return rate as a mantissa between [0, 1e18] | function _intervalRewardRate(
uint256 _rateMantissa,
uint256 _timeDelta
| function _intervalRewardRate(
uint256 _rateMantissa,
uint256 _timeDelta
| 17,577 |
128 | // deploying minimal proxy contracts, also known as "clones". > To simply and cheaply clone contract functionality in an immutable way, this standard specifies> a minimal bytecode implementation that delegates all calls to a known, fixed address. The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`(salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using thedeterministic method. / | library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
| library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
| 69,640 |
88 | // Check if claim period is active | require(now >= CLAIM_START_DATE);
require(now < CLAIM_END_DATE);
| require(now >= CLAIM_START_DATE);
require(now < CLAIM_END_DATE);
| 36,374 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.