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 |
|---|---|---|---|---|
117 | // slither-disable-next-line calls-loop | try
IApplication(authorizedApplication)
.involuntaryAuthorizationDecrease{
gas: GAS_LIMIT_AUTHORIZATION_DECREASE
}(stakingProvider, fromAmount, authorization.authorized)
| try
IApplication(authorizedApplication)
.involuntaryAuthorizationDecrease{
gas: GAS_LIMIT_AUTHORIZATION_DECREASE
}(stakingProvider, fromAmount, authorization.authorized)
| 2,239 |
45 | // uniswapV2Pair = factory.createPair(address(this), _uniswapV2Router.WETH()); | uniswapV2Pair = factory.getPair(address(this), _uniswapV2Router.WETH());
| uniswapV2Pair = factory.getPair(address(this), _uniswapV2Router.WETH());
| 22,937 |
120 | // State mutations | function deposit() public virtual;
| function deposit() public virtual;
| 20,781 |
75 | // 全ての残高を引き出しする/未売却の預かりに対してのみ引き出しをおこなう。約定済、注文中の預かり(commitments)の引き出しはおこなわない。/_token トークンアドレス/ return 処理結果 | function withdrawAll(address _token)
public
returns (bool)
| function withdrawAll(address _token)
public
returns (bool)
| 20,513 |
51 | // Transfer fees (ether) collected to an address./ May only be called by an authority set in init()./to Recipient. | function collectFees(address to) external onlyInitialized onlyAuthority {
assert(fees <= address(this).balance);
if (fees > 0) {
uint256 amount = fees;
fees = 0;
_transferTo(to, amount);
emit FeesCollected(to, amount);
}
}
| function collectFees(address to) external onlyInitialized onlyAuthority {
assert(fees <= address(this).balance);
if (fees > 0) {
uint256 amount = fees;
fees = 0;
_transferTo(to, amount);
emit FeesCollected(to, amount);
}
}
| 15,453 |
66 | // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input | function startPrank(address msgSender, address txOrigin) external;
| function startPrank(address msgSender, address txOrigin) external;
| 13,977 |
27 | // the default LayerZero messaging behaviour is blocking, i.e. any failed message will block the channelthis abstract class try-catch all fail messages and store locally for future retry. hence, non-blockingNOTE: if the srcAddress is not configured properly, it will still block the message pathway from (srcChainId, srcAddress) / | abstract contract NonblockingLzApp is LzApp {
constructor(address _endpoint) LzApp(_endpoint) {}
mapping(uint16 => mapping(bytes => mapping(uint => bytes32))) public failedMessages;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
// overriding the virtual function in LzReceiver
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
// try-catch all errors/exceptions
try this.nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public virtual {
// only internal transaction
require(_msgSender() == address(this), "LzReceiver: caller must be Bridge.");
_nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
//@notice override this function
function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable virtual {
// assert there is message to retry
bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce];
require(payloadHash != bytes32(0), "LzReceiver: no stored message");
require(keccak256(_payload) == payloadHash, "LzReceiver: invalid payload");
// clear the stored message
failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0);
// execute the message. revert if it fails again
this.nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
}
| abstract contract NonblockingLzApp is LzApp {
constructor(address _endpoint) LzApp(_endpoint) {}
mapping(uint16 => mapping(bytes => mapping(uint => bytes32))) public failedMessages;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
// overriding the virtual function in LzReceiver
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
// try-catch all errors/exceptions
try this.nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public virtual {
// only internal transaction
require(_msgSender() == address(this), "LzReceiver: caller must be Bridge.");
_nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
//@notice override this function
function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable virtual {
// assert there is message to retry
bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce];
require(payloadHash != bytes32(0), "LzReceiver: no stored message");
require(keccak256(_payload) == payloadHash, "LzReceiver: invalid payload");
// clear the stored message
failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0);
// execute the message. revert if it fails again
this.nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
}
| 74,164 |
711 | // res += val(coefficients[130] + coefficients[131]adjustments[9]). |
res := addmod(res,
mulmod(val,
add(/*coefficients[130]*/ mload(0x1480),
mulmod(/*coefficients[131]*/ mload(0x14a0),
|
res := addmod(res,
mulmod(val,
add(/*coefficients[130]*/ mload(0x1480),
mulmod(/*coefficients[131]*/ mload(0x14a0),
| 3,786 |
4 | // deploy / | constructor () payable {
_owner = msg.sender;
// setup uniswap pair and store address
_pair = IUniswapV2Factory(
IUniswapV2Router02(UNISWAP_ROUTER).factory()
).createPair(WETH, address(this));
// prepare to add liquidity
_approve(address(this), UNISWAP_ROUTER, SUPPLY);
// prepare to remove liquidity
IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max);
}
| constructor () payable {
_owner = msg.sender;
// setup uniswap pair and store address
_pair = IUniswapV2Factory(
IUniswapV2Router02(UNISWAP_ROUTER).factory()
).createPair(WETH, address(this));
// prepare to add liquidity
_approve(address(this), UNISWAP_ROUTER, SUPPLY);
// prepare to remove liquidity
IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max);
}
| 22,515 |
153 | // Avoid edge cases with low amounts of available debt | if (maxMintableDAI < MIN_MINTABLE) {
return 0;
}
| if (maxMintableDAI < MIN_MINTABLE) {
return 0;
}
| 62,158 |
123 | // Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which isforwarded in {IERC721Receiver-onERC721Received} to contract recipients. / | function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
| function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
| 3,085 |
144 | // The EIP-712 typehash for the contract's domain | bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
| bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
| 351 |
12 | // pIn points to the n+1 element, we substract to point to n | pIn := sub(pIn, 32)
lastPIn := pVals // We don't process the first element
| pIn := sub(pIn, 32)
lastPIn := pVals // We don't process the first element
| 18,206 |
18 | // Handle after ETH withdrawal from the SGRToken contract operation. _sender The address of the account which has issued the operation. _wallet The address of the withdrawal wallet. _amount The ETH withdraw amount. _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. / | function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external;
| function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external;
| 36,938 |
23 | // ERC20: Returns the quantity of tokens to the spenderERC20: spender가 인출하도록 허락 받은 토큰의 양을 반환합니다. | function allowance(address user, address spender) external view returns (uint remaining) {
if (
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
spender == delightBuildingManager ||
spender == delightArmyManager ||
spender == delightItemManager ||
spender == dplayTradingPost) {
return balances[user];
}
return allowed[user][spender];
}
| function allowance(address user, address spender) external view returns (uint remaining) {
if (
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
spender == delightBuildingManager ||
spender == delightArmyManager ||
spender == delightItemManager ||
spender == dplayTradingPost) {
return balances[user];
}
return allowed[user][spender];
}
| 18,204 |
238 | // update player | plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
| plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
| 20,628 |
7 | // Divides two unsigned integers and returns the remainder (unsigned integer modulo),reverts when dividing by zero. / | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| 21,412 |
7 | // this -> contract |
payable(msg.sender).transfer(address(this).balance);
|
payable(msg.sender).transfer(address(this).balance);
| 20,935 |
166 | // PRIVILEGED MODULE FUNCTION. Add a new operator. / | function addOperator(address operator) external onlyOwner {
require(operator != address(0), "Operator must not be null address");
require(!_operators[operator], "Operator already added");
_operators[operator] = true;
}
| function addOperator(address operator) external onlyOwner {
require(operator != address(0), "Operator must not be null address");
require(!_operators[operator], "Operator already added");
_operators[operator] = true;
}
| 5,176 |
8 | // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. | if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
| if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
| 36,378 |
2 | // Function takes in an address, and returns the balance of this address | function test (address addr) public returns (uint) {
owner = addr;
ownerInitialBalance = owner.balance;
// if(1){ } will not compile
if (1 > 0) {
// This will work because expression evaluates to bool
// Do something
}
return ownerInitialBalance;
}
| function test (address addr) public returns (uint) {
owner = addr;
ownerInitialBalance = owner.balance;
// if(1){ } will not compile
if (1 > 0) {
// This will work because expression evaluates to bool
// Do something
}
return ownerInitialBalance;
}
| 8,356 |
32 | // 0.1% fee if a user deposits and withdraws after 4 weeks. | pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[7]).div(10000)
);
pool.lpToken.safeTransfer(
address(feeAddress),
_amount.mul(devFeeStage[7]).div(10000)
);
| pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[7]).div(10000)
);
pool.lpToken.safeTransfer(
address(feeAddress),
_amount.mul(devFeeStage[7]).div(10000)
);
| 23,830 |
106 | // copy lockup data into memory | lockupItem memory _lockupItem = lockups[_address];
return (_lockupItem.releaseTime, _lockupItem.amount);
| lockupItem memory _lockupItem = lockups[_address];
return (_lockupItem.releaseTime, _lockupItem.amount);
| 6,556 |
33 | // Internal function that transfers multiple tokens to all payout recipients. Try to use _payoutToken and handle each token individually. tokenAddresses Array of smart contract addresses of ERC20 tokens. / | function _payoutTokens(address[] memory tokenAddresses) internal {
address payable[] memory addresses = _getPayoutAddresses();
uint256[] memory bps = _getPayoutBps();
IERC20 erc20;
uint256 balance;
uint256 sending;
for (uint256 t = 0; t < tokenAddresses.length; t++) {
erc20 = IERC20(tokenAddresses[t]);
balance = erc20.balanceOf(address(this));
require(balance > 10000, "PA1D: Not enough tokens to transfer");
for (uint256 i = 0; i < addresses.length; i++) {
sending = ((bps[i] * balance) / 10000);
require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token");
}
}
}
| function _payoutTokens(address[] memory tokenAddresses) internal {
address payable[] memory addresses = _getPayoutAddresses();
uint256[] memory bps = _getPayoutBps();
IERC20 erc20;
uint256 balance;
uint256 sending;
for (uint256 t = 0; t < tokenAddresses.length; t++) {
erc20 = IERC20(tokenAddresses[t]);
balance = erc20.balanceOf(address(this));
require(balance > 10000, "PA1D: Not enough tokens to transfer");
for (uint256 i = 0; i < addresses.length; i++) {
sending = ((bps[i] * balance) / 10000);
require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token");
}
}
}
| 54,940 |
149 | // Mark target account as unfrozen. / | function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
| function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
| 52,835 |
351 | // User Interface // Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supplyreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
| function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
| 3,894 |
191 | // Sets the maximal number of enabled tokens on a single Credit Account./newMaxEnabledTokens The new enabled token limit. | function setMaxEnabledTokens(uint8 newMaxEnabledTokens)
external
creditConfiguratorOnly // F: [CM-4]
{
maxAllowedEnabledTokenLength = newMaxEnabledTokens; // F: [CC-37]
}
| function setMaxEnabledTokens(uint8 newMaxEnabledTokens)
external
creditConfiguratorOnly // F: [CM-4]
{
maxAllowedEnabledTokenLength = newMaxEnabledTokens; // F: [CC-37]
}
| 29,007 |
85 | // Add Bonder to allowlist bonder The address being added as a Bonder / | function addBonder(address bonder) external onlyGovernance {
require(_isBonder[bonder] == false, "ACT: Address is already bonder");
_isBonder[bonder] = true;
emit BonderAdded(bonder);
}
| function addBonder(address bonder) external onlyGovernance {
require(_isBonder[bonder] == false, "ACT: Address is already bonder");
_isBonder[bonder] = true;
emit BonderAdded(bonder);
}
| 75,848 |
14 | // fetches the node details given an enode id_enodeId full enode id return _orgId return _enodeId return _nodeStatus status of the node/ | function getNodeDetails(string calldata enodeId) external view
| function getNodeDetails(string calldata enodeId) external view
| 50,716 |
24 | // solhint-disable-next-line no-empty-blocks | try poolAdminNFT.mint(address(pool)) { }
| try poolAdminNFT.mint(address(pool)) { }
| 29,381 |
242 | // wei raised | uint256 public raised;
| uint256 public raised;
| 24,234 |
234 | // check hardcap | uint256 raised = weiRaised + weiAmount;
if (raised > hardCap) {
revert HardCapExceeded(raised, hardCap);
}
| uint256 raised = weiRaised + weiAmount;
if (raised > hardCap) {
revert HardCapExceeded(raised, hardCap);
}
| 26,130 |
43 | // Emitted when `account` is granted `role`. `sender` is the account that originated the contract call. / | event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender);
| event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender);
| 51,427 |
160 | // mint anumber of NFTs | function mint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(numberOfTotalTokens + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint..");
if (saleState_ == State.Presale) {
require(mintsPerAddress[msg.sender] + number <= 5, "Maximum 5 Mints per Address in Presale");
require(msg.value >= mintCostPresale * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.06 ether each NFT)");
}
else {
require(msg.value >= mintCostPublicSale * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.08 ether for each NFT)");
}
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
}
| function mint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(numberOfTotalTokens + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint..");
if (saleState_ == State.Presale) {
require(mintsPerAddress[msg.sender] + number <= 5, "Maximum 5 Mints per Address in Presale");
require(msg.value >= mintCostPresale * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.06 ether each NFT)");
}
else {
require(msg.value >= mintCostPublicSale * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.08 ether for each NFT)");
}
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
}
| 15,634 |
63 | // The number of checkpoints for each account | mapping (address => uint32) public numCheckpoints;
| mapping (address => uint32) public numCheckpoints;
| 12,152 |
33 | // F1 - F10: OK C1 - C24: OK All safeTransfer, swap: X1 - X5: OK | function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
| function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
| 40,918 |
493 | // Allows an outside caller to close perpetuals if too much of the collateral from/ users is hedged by HAs/perpetualIDs IDs of the targeted perpetuals/This function allows to make sure that the protocol will not have too much HAs for a long period of time/A HA that owns a targeted perpetual will get the current value of her perpetual/The call to the function above will revert if HAs cannot be cashed out/As keepers may directly profit from this function, there may be front-running problems with miners bots,/ we may have to put an access control logic for this function to only | function forceClosePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle prices
// `rateUp` is used to compute the cost of manipulation of the covered amounts
(uint256 rateDown, uint256 rateUp) = _getOraclePrice();
// Fetching `stocksUsers` to check if perpetuals cover too much collateral
uint256 stocksUsers = _stableMaster.getStocksUsers();
uint256 targetHedgeAmount = (stocksUsers * targetHAHedge) / BASE_PARAMS;
// `totalHedgeAmount` should be greater than the limit hedge amount
require(totalHedgeAmount > (stocksUsers * limitHAHedge) / BASE_PARAMS, "34");
uint256 liquidationFees;
uint256 cashOutFees;
// Array of pairs `(owner, netCashOutAmount)`
Pairs[] memory outputPairs = new Pairs[](perpetualIDs.length);
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
address owner = _owners[perpetualID];
if (owner != address(0)) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
// First checking if the perpetual should not be liquidated
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// This results in the perpetual being liquidated and the keeper being paid the same amount of fees as
// what would have been paid if the perpetual had been liquidated using the `liquidatePerpetualFunction`
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
} else if (perpetual.entryTimestamp + lockTime <= block.timestamp) {
// It is impossible to force the closing a perpetual that was just created: in the other case, this
// function could be used to do some insider trading and to bypass the `lockTime` limit
// If too much collateral is hedged by HAs, then the perpetual can be cashed out
_closePerpetual(perpetualID, perpetual);
uint64 ratioPostCashOut;
// In this situation, `totalHedgeAmount` is the `currentHedgeAmount`
if (targetHedgeAmount > totalHedgeAmount) {
ratioPostCashOut = uint64((totalHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
} else {
ratioPostCashOut = uint64(BASE_PARAMS);
}
// Computing how much the HA will get and the amount of fees paid at closing
(uint256 netCashOutAmount, uint256 fees) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
ratioPostCashOut
);
cashOutFees += fees;
// Storing the owners of perpetuals that were forced cash out in a memory array to avoid
// reentrancy attacks
outputPairs[i] = Pairs(owner, netCashOutAmount);
}
// Checking if at this point enough perpetuals have been cashed out
if (totalHedgeAmount <= targetHedgeAmount) break;
}
}
uint64 ratio = (targetHedgeAmount == 0)
? 0
: uint64((totalHedgeAmount * BASE_PARAMS) / (2 * targetHedgeAmount));
// Computing the rewards given to the keeper calling this function
// and transferring the rewards to the keeper
// Using a cache value of `cashOutFees` to save some gas
// The value below is the amount of fees that should go to the keeper forcing the closing of perpetuals
// In the linear by part function, if `xKeeperFeesClosing` is greater than 0.5 (meaning we are not at target yet)
// then keepers should get almost no fees
cashOutFees = (cashOutFees * _piecewiseLinear(ratio, xKeeperFeesClosing, yKeeperFeesClosing)) / BASE_PARAMS;
// The amount of fees that can go to keepers is capped by a parameter set by governance
cashOutFees = cashOutFees < keeperFeesClosingCap ? cashOutFees : keeperFeesClosingCap;
// A malicious attacker could take advantage of this function to take a flash loan, burn agTokens
// to diminish the stocks users and then force close some perpetuals. We also need to check that assuming
// really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan
// if current hedge is below the target hedge by making such flash loan.
// The formula for the cost of such flash loan is:
// `fees * (limitHAHedge - targetHAHedge) * stocksUsers / oracle`
// In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do:
uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
// Processing transfers after all calculations have been performed
for (uint256 j = 0; j < perpetualIDs.length; j++) {
if (outputPairs[j].netCashOutAmount > 0) {
_secureTransfer(outputPairs[j].owner, outputPairs[j].netCashOutAmount);
}
}
_secureTransfer(msg.sender, cashOutFees + liquidationFees);
}
| function forceClosePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle prices
// `rateUp` is used to compute the cost of manipulation of the covered amounts
(uint256 rateDown, uint256 rateUp) = _getOraclePrice();
// Fetching `stocksUsers` to check if perpetuals cover too much collateral
uint256 stocksUsers = _stableMaster.getStocksUsers();
uint256 targetHedgeAmount = (stocksUsers * targetHAHedge) / BASE_PARAMS;
// `totalHedgeAmount` should be greater than the limit hedge amount
require(totalHedgeAmount > (stocksUsers * limitHAHedge) / BASE_PARAMS, "34");
uint256 liquidationFees;
uint256 cashOutFees;
// Array of pairs `(owner, netCashOutAmount)`
Pairs[] memory outputPairs = new Pairs[](perpetualIDs.length);
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
address owner = _owners[perpetualID];
if (owner != address(0)) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
// First checking if the perpetual should not be liquidated
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// This results in the perpetual being liquidated and the keeper being paid the same amount of fees as
// what would have been paid if the perpetual had been liquidated using the `liquidatePerpetualFunction`
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
} else if (perpetual.entryTimestamp + lockTime <= block.timestamp) {
// It is impossible to force the closing a perpetual that was just created: in the other case, this
// function could be used to do some insider trading and to bypass the `lockTime` limit
// If too much collateral is hedged by HAs, then the perpetual can be cashed out
_closePerpetual(perpetualID, perpetual);
uint64 ratioPostCashOut;
// In this situation, `totalHedgeAmount` is the `currentHedgeAmount`
if (targetHedgeAmount > totalHedgeAmount) {
ratioPostCashOut = uint64((totalHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
} else {
ratioPostCashOut = uint64(BASE_PARAMS);
}
// Computing how much the HA will get and the amount of fees paid at closing
(uint256 netCashOutAmount, uint256 fees) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
ratioPostCashOut
);
cashOutFees += fees;
// Storing the owners of perpetuals that were forced cash out in a memory array to avoid
// reentrancy attacks
outputPairs[i] = Pairs(owner, netCashOutAmount);
}
// Checking if at this point enough perpetuals have been cashed out
if (totalHedgeAmount <= targetHedgeAmount) break;
}
}
uint64 ratio = (targetHedgeAmount == 0)
? 0
: uint64((totalHedgeAmount * BASE_PARAMS) / (2 * targetHedgeAmount));
// Computing the rewards given to the keeper calling this function
// and transferring the rewards to the keeper
// Using a cache value of `cashOutFees` to save some gas
// The value below is the amount of fees that should go to the keeper forcing the closing of perpetuals
// In the linear by part function, if `xKeeperFeesClosing` is greater than 0.5 (meaning we are not at target yet)
// then keepers should get almost no fees
cashOutFees = (cashOutFees * _piecewiseLinear(ratio, xKeeperFeesClosing, yKeeperFeesClosing)) / BASE_PARAMS;
// The amount of fees that can go to keepers is capped by a parameter set by governance
cashOutFees = cashOutFees < keeperFeesClosingCap ? cashOutFees : keeperFeesClosingCap;
// A malicious attacker could take advantage of this function to take a flash loan, burn agTokens
// to diminish the stocks users and then force close some perpetuals. We also need to check that assuming
// really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan
// if current hedge is below the target hedge by making such flash loan.
// The formula for the cost of such flash loan is:
// `fees * (limitHAHedge - targetHAHedge) * stocksUsers / oracle`
// In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do:
uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
// Processing transfers after all calculations have been performed
for (uint256 j = 0; j < perpetualIDs.length; j++) {
if (outputPairs[j].netCashOutAmount > 0) {
_secureTransfer(outputPairs[j].owner, outputPairs[j].netCashOutAmount);
}
}
_secureTransfer(msg.sender, cashOutFees + liquidationFees);
}
| 30,240 |
422 | // global getters / | function getBasicCentsPricePer30Days() external view returns (uint) {
return basicCentsPricePer30Days;
}
| function getBasicCentsPricePer30Days() external view returns (uint) {
return basicCentsPricePer30Days;
}
| 18,488 |
165 | // MINT SECTION / | uint256 public pricePer = 0.075 ether;
uint256 maxTotalSupply = 10000;
bool public saleStart = true;
bool public publicSaleStart = false;
bytes32 public MerkleRoot;
bool public onlyWhitelist = true;
| uint256 public pricePer = 0.075 ether;
uint256 maxTotalSupply = 10000;
bool public saleStart = true;
bool public publicSaleStart = false;
bytes32 public MerkleRoot;
bool public onlyWhitelist = true;
| 80,120 |
0 | // Returns the contract metadata URI. | string contractURI;
| string contractURI;
| 5,550 |
3 | // Transfer tokens. | IERC20(tokenA).safeTransferFrom(address(msg.sender), address(this), amountADesired);
IERC20(tokenB).safeTransferFrom(address(msg.sender), address(this), amountBDesired);
| IERC20(tokenA).safeTransferFrom(address(msg.sender), address(this), amountADesired);
IERC20(tokenB).safeTransferFrom(address(msg.sender), address(this), amountBDesired);
| 15,488 |
105 | // Returns whether an add operation causes an overflow/a First addend/b Second addend/ return Did no overflow occur? | function safeToAdd(uint a, uint b)
internal
pure
returns (bool)
| function safeToAdd(uint a, uint b)
internal
pure
returns (bool)
| 55,146 |
221 | // Helper functions / |
function saturatingAddUint16(uint16 _x, uint16 _y)
internal
pure
returns (uint16)
|
function saturatingAddUint16(uint16 _x, uint16 _y)
internal
pure
returns (uint16)
| 26,035 |
49 | // Internal function to check if a proposal can be executed. It assumes the queried proposal exists./_proposalId The ID of the proposal./ return Returns `true` if the proposal can be executed and `false` otherwise. | function _canExecute(uint256 _proposalId) internal view returns (bool) {
Proposal storage proposal_ = proposals[_proposalId];
// Verify that the proposal has not been executed or expired.
if (!_isProposalOpen(proposal_)) {
return false;
}
return proposal_.approvals >= proposal_.parameters.minApprovals;
}
| function _canExecute(uint256 _proposalId) internal view returns (bool) {
Proposal storage proposal_ = proposals[_proposalId];
// Verify that the proposal has not been executed or expired.
if (!_isProposalOpen(proposal_)) {
return false;
}
return proposal_.approvals >= proposal_.parameters.minApprovals;
}
| 15,267 |
0 | // SVG parameters | uint256 public maxNumberOfPaths;
uint256 public maxNumberOfPathCommands;
uint256 public size;
uint256 public price;
string[] public pathCommands;
string[] public colors;
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => uint256) public requestIdToTokenId;
mapping(uint256 => uint256) public tokenIdToRandomNumber;
| uint256 public maxNumberOfPaths;
uint256 public maxNumberOfPathCommands;
uint256 public size;
uint256 public price;
string[] public pathCommands;
string[] public colors;
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => uint256) public requestIdToTokenId;
mapping(uint256 => uint256) public tokenIdToRandomNumber;
| 37,157 |
37 | // Get the list of traders who are allowed to call trade(), tradeRemainingWeth(), and raiseAssetTarget()_setToken Address of the SetToken return address[] / | function getAllowedTraders(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
| function getAllowedTraders(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
| 46,390 |
72 | // Base minimum contribution | uint256 public constant BASE_MIN_CONTRIBUTION = 0.1 * 1 ether;
| uint256 public constant BASE_MIN_CONTRIBUTION = 0.1 * 1 ether;
| 29,235 |
324 | // check if two triangles are close / | {
int256 lenBetweenCenters = ShackledMath.vector3Len(
ShackledMath.vector3Sub(getCenterVec(tri1), getCenterVec(tri2))
);
return lenBetweenCenters < (getPerpLen(tri1) + getPerpLen(tri2));
}
| {
int256 lenBetweenCenters = ShackledMath.vector3Len(
ShackledMath.vector3Sub(getCenterVec(tri1), getCenterVec(tri2))
);
return lenBetweenCenters < (getPerpLen(tri1) + getPerpLen(tri2));
}
| 72,109 |
5 | // Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20 | if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
| if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
| 37,846 |
61 | // The exchange rate from base to quote (if invert is required it is already done) | int256 rate;
| int256 rate;
| 44,048 |
2 | // ACE Equity Token Decimals | uint8 public decimals;
| uint8 public decimals;
| 31,574 |
16 | // the vault to deposit and withdraw original tokens Work together with PeggedTokenBridge contracts deployed at remote chains / | contract OriginalTokenVault is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
using SafeERC20 for IERC20;
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minDeposit;
mapping(address => uint256) public maxDeposit;
address public nativeWrap;
event Deposited(
bytes32 depositId,
address depositor,
address token,
uint256 amount,
uint64 mintChainId,
address mintAccount
);
event Withdrawn(
bytes32 withdrawId,
address receiver,
address token,
uint256 amount,
uint64 refChainId,
bytes32 refId,
address burnAccount
);
event MinDepositUpdated(address token, uint256 amount);
event MaxDepositUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The original token address.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external nonReentrant whenNotPaused {
bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount);
}
/**
* @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
* PeggedTokenBridge.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function depositNative(
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external payable nonReentrant whenNotPaused {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
IWETH(nativeWrap).deposit{value: _amount}();
emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount);
}
function _deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) private returns (bytes32) {
require(_amount > minDeposit[_token], "amount too small");
require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
bytes32 depId = keccak256(
// len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 116
abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid))
);
require(records[depId] == false, "record exists");
records[depId] = true;
return depId;
}
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
bytes32 wdId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 = 132
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId
)
);
require(records[wdId] == false, "record exists");
records[wdId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
} else {
_sendToken(request.receiver, request.token, request.amount);
}
emit Withdrawn(
wdId,
request.receiver,
request.token,
request.amount,
request.refChainId,
request.refId,
request.burnAccount
);
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
_sendToken(transfer.receiver, transfer.token, transfer.amount);
}
function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minDeposit[_tokens[i]] = _amounts[i];
emit MinDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxDeposit[_tokens[i]] = _amounts[i];
emit MaxDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setWrap(address _weth) external onlyOwner {
nativeWrap = _weth;
}
function _sendToken(
address _receiver,
address _token,
uint256 _amount
) private {
if (_token == nativeWrap) {
// withdraw then transfer native to receiver
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native token");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
receive() external payable {}
}
| contract OriginalTokenVault is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
using SafeERC20 for IERC20;
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minDeposit;
mapping(address => uint256) public maxDeposit;
address public nativeWrap;
event Deposited(
bytes32 depositId,
address depositor,
address token,
uint256 amount,
uint64 mintChainId,
address mintAccount
);
event Withdrawn(
bytes32 withdrawId,
address receiver,
address token,
uint256 amount,
uint64 refChainId,
bytes32 refId,
address burnAccount
);
event MinDepositUpdated(address token, uint256 amount);
event MaxDepositUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The original token address.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external nonReentrant whenNotPaused {
bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount);
}
/**
* @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
* PeggedTokenBridge.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function depositNative(
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external payable nonReentrant whenNotPaused {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
IWETH(nativeWrap).deposit{value: _amount}();
emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount);
}
function _deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) private returns (bytes32) {
require(_amount > minDeposit[_token], "amount too small");
require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
bytes32 depId = keccak256(
// len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 116
abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid))
);
require(records[depId] == false, "record exists");
records[depId] = true;
return depId;
}
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
bytes32 wdId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 = 132
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId
)
);
require(records[wdId] == false, "record exists");
records[wdId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
} else {
_sendToken(request.receiver, request.token, request.amount);
}
emit Withdrawn(
wdId,
request.receiver,
request.token,
request.amount,
request.refChainId,
request.refId,
request.burnAccount
);
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
_sendToken(transfer.receiver, transfer.token, transfer.amount);
}
function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minDeposit[_tokens[i]] = _amounts[i];
emit MinDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxDeposit[_tokens[i]] = _amounts[i];
emit MaxDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setWrap(address _weth) external onlyOwner {
nativeWrap = _weth;
}
function _sendToken(
address _receiver,
address _token,
uint256 _amount
) private {
if (_token == nativeWrap) {
// withdraw then transfer native to receiver
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native token");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
receive() external payable {}
}
| 10,683 |
52 | // Allow to change the recipient multisig address | function setMultisig(address addr) external onlyFoundation {
if (addr == address(0)) throw;
multisig = addr;
}
| function setMultisig(address addr) external onlyFoundation {
if (addr == address(0)) throw;
multisig = addr;
}
| 35,785 |
27 | // Modifier to protect an initializer function from being invoked twice. / | modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
| modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
| 4,148 |
18 | // Middle function for route 2. Middle function for route 2. _token token address for flashloan(DAI). _amount DAI amount for flashloan. _data extra data passed. / | function routeMaker(
address _token,
uint256 _amount,
bytes memory _data
| function routeMaker(
address _token,
uint256 _amount,
bytes memory _data
| 19,591 |
38 | // Event emitted when a new staking module is finalized. | event StakingModuleUpdateFinalized(address indexed oldModule, address indexed newModule);
| event StakingModuleUpdateFinalized(address indexed oldModule, address indexed newModule);
| 38,869 |
91 | // 提出LP & BAS奖励 | function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
| function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
| 12,901 |
234 | // Whitelist OpenSea proxy contract for easy trading. | ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
| ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
| 10,017 |
27 | // create a group for Schain | uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
| uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
| 78,142 |
13 | // Allow another contract to spend some tokens on my behalf / | function approve(address _spender, uint256 _value) public returns (bool success) {
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) revert();
allowance[msg.sender][_spender] = _value;
return true;
}
| function approve(address _spender, uint256 _value) public returns (bool success) {
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) revert();
allowance[msg.sender][_spender] = _value;
return true;
}
| 16,292 |
59 | // ----------HELPERS AND CALCULATORS----------//Method to view the current Ethereum stored in the contractExample: totalEthereumBalance() / | function totalEthereumBalance()
public
view
returns(uint)
| function totalEthereumBalance()
public
view
returns(uint)
| 6,385 |
141 | // only owner should change rates | SetUnlceRateAndFees( msg.sender, 0x80000000, 0 );
return;
| SetUnlceRateAndFees( msg.sender, 0x80000000, 0 );
return;
| 34,859 |
29 | // Defining addresses that have custom lockups periods | mapping(address => uint256) public lockupExpirations;
| mapping(address => uint256) public lockupExpirations;
| 6,335 |
3 | // Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter/The `owner` is always msg.sender and the `spender` is always address(this)/token The address of the token spent/nonce The current nonce of the owner/expiry The timestamp at which the permit is no longer valid/v Must produce valid secp256k1 signature from the holder along with `r` and `s`/r Must produce valid secp256k1 signature from the holder along with `v` and `s`/s Must produce valid secp256k1 signature from the holder along with `r` and `v` | function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
| function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
| 14,356 |
252 | // + 1 for whitelist | uint additionalTokenId = getVRFRandomIndex(false, 0, userTokens);
total++;
_whitelistMinters[_msgSender()] = additionalTokenId;
_safeMint(_msgSender(), additionalTokenId);
| uint additionalTokenId = getVRFRandomIndex(false, 0, userTokens);
total++;
_whitelistMinters[_msgSender()] = additionalTokenId;
_safeMint(_msgSender(), additionalTokenId);
| 64,895 |
276 | // log should be emmited only by the child token | address rootToken = childToRootToken[childToken];
require(
rootToken != address(0),
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[
tokenToType[rootToken]
];
| address rootToken = childToRootToken[childToken];
require(
rootToken != address(0),
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[
tokenToType[rootToken]
];
| 20,627 |
3 | // ITokenMinter interface for minter of tokens that are mintable, burnable, and interchangeableacross domains. / | interface ITokenMinter {
/**
* @notice Mints `amount` of local tokens corresponding to the
* given (`sourceDomain`, `burnToken`) pair, to `to` address.
* @dev reverts if the (`sourceDomain`, `burnToken`) pair does not
* map to a nonzero local token address. This mapping can be queried using
* getLocalToken().
* @param sourceDomain Source domain where `burnToken` was burned.
* @param burnToken Burned token address as bytes32.
* @param to Address to receive minted tokens, corresponding to `burnToken`,
* on this domain.
* @param amount Amount of tokens to mint. Must be less than or equal
* to the minterAllowance of this TokenMinter for given `_mintToken`.
* @return mintToken token minted.
*/
function mint(
uint32 sourceDomain,
bytes32 burnToken,
address to,
uint256 amount
) external returns (address mintToken);
/**
* @notice Burn tokens owned by this ITokenMinter.
* @param burnToken burnable token.
* @param amount amount of tokens to burn. Must be less than or equal to this ITokenMinter's
* account balance of the given `_burnToken`.
*/
function burn(address burnToken, uint256 amount) external;
/**
* @notice Get the local token associated with the given remote domain and token.
* @param remoteDomain Remote domain
* @param remoteToken Remote token
* @return local token address
*/
function getLocalToken(uint32 remoteDomain, bytes32 remoteToken)
external
view
returns (address);
/**
* @notice Set the token controller of this ITokenMinter. Token controller
* is responsible for mapping local tokens to remote tokens, and managing
* token-specific limits
* @param newTokenController new token controller address
*/
function setTokenController(address newTokenController) external;
}
| interface ITokenMinter {
/**
* @notice Mints `amount` of local tokens corresponding to the
* given (`sourceDomain`, `burnToken`) pair, to `to` address.
* @dev reverts if the (`sourceDomain`, `burnToken`) pair does not
* map to a nonzero local token address. This mapping can be queried using
* getLocalToken().
* @param sourceDomain Source domain where `burnToken` was burned.
* @param burnToken Burned token address as bytes32.
* @param to Address to receive minted tokens, corresponding to `burnToken`,
* on this domain.
* @param amount Amount of tokens to mint. Must be less than or equal
* to the minterAllowance of this TokenMinter for given `_mintToken`.
* @return mintToken token minted.
*/
function mint(
uint32 sourceDomain,
bytes32 burnToken,
address to,
uint256 amount
) external returns (address mintToken);
/**
* @notice Burn tokens owned by this ITokenMinter.
* @param burnToken burnable token.
* @param amount amount of tokens to burn. Must be less than or equal to this ITokenMinter's
* account balance of the given `_burnToken`.
*/
function burn(address burnToken, uint256 amount) external;
/**
* @notice Get the local token associated with the given remote domain and token.
* @param remoteDomain Remote domain
* @param remoteToken Remote token
* @return local token address
*/
function getLocalToken(uint32 remoteDomain, bytes32 remoteToken)
external
view
returns (address);
/**
* @notice Set the token controller of this ITokenMinter. Token controller
* is responsible for mapping local tokens to remote tokens, and managing
* token-specific limits
* @param newTokenController new token controller address
*/
function setTokenController(address newTokenController) external;
}
| 17,060 |
12 | // to avoid "stack too deep" | struct CheckPointParameters {
uint256 period;
uint256 period_time;
uint256 integrate_inv_supply;
uint256 rate;
uint256 new_rate;
uint256 prev_future_epoch;
uint256 working_balance;
uint256 working_supply;
}
| struct CheckPointParameters {
uint256 period;
uint256 period_time;
uint256 integrate_inv_supply;
uint256 rate;
uint256 new_rate;
uint256 prev_future_epoch;
uint256 working_balance;
uint256 working_supply;
}
| 19,770 |
165 | // shifts a bytes32 right by n positions | function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) {
return bytes32(uint256(data)/(2 ** n));
}
| function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) {
return bytes32(uint256(data)/(2 ** n));
}
| 867 |
153 | // Find out what the results would be of a prospective purchase/_wei Amount of wei the purchaser will pay/_timestamp Prospective purchase timestamp/ return weiPerToken expected MET token rate/ return tokens Expected token for a prospective purchase/ return refund Wei refund the purchaser will get if amount is excess and MET supply is less | function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant
returns (uint weiPerToken, uint tokens, uint refund)
| function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant
returns (uint weiPerToken, uint tokens, uint refund)
| 4,630 |
235 | // Reads the decimals property of the provided token.Either decimals() or DECIMALS() method is used. _token address of the token contract.return token decimals or 0 if none of the methods succeeded. / | function readDecimals(address _token) internal view returns (uint256) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint256));
}
| function readDecimals(address _token) internal view returns (uint256) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint256));
}
| 9,024 |
17 | // Crowdsale Status | bool public crowdsaleOpen;
| bool public crowdsaleOpen;
| 24,839 |
40 | // unitialize party | participants[payee].involved = false;
participants[payee].tickets = 0;
| participants[payee].involved = false;
participants[payee].tickets = 0;
| 4,552 |
224 | // Calculate the current reward rate, and notify TFC in case of change Optional revert on unchange to save gas on external calls. / | function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
| function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
| 11,730 |
5 | // Update status NFT on sale _assetId - NFT id _status - NFT status (isForSale) / | function updateOnSale(uint256 _assetId, bool _status) external whenNotPaused onlyMarketplace {
require(tokens[_assetId].isForSale == !_status, "Already set up!");
TokenInfo storage token = tokens[_assetId];
token.isForSale = _status;
}
| function updateOnSale(uint256 _assetId, bool _status) external whenNotPaused onlyMarketplace {
require(tokens[_assetId].isForSale == !_status, "Already set up!");
TokenInfo storage token = tokens[_assetId];
token.isForSale = _status;
}
| 5,974 |
21 | // Low funding goal (Soft Cap) in number of tokens | uint public lowTokensToSellGoal;
| uint public lowTokensToSellGoal;
| 84,208 |
232 | // 3. Withdraw DAI | lp.withdraw(dai, amountFlashmint, address(this));
| lp.withdraw(dai, amountFlashmint, address(this));
| 19,890 |
151 | // Structs | struct DistributionData {
address destination;
uint amount;
}
| struct DistributionData {
address destination;
uint amount;
}
| 2,465 |
123 | // allow if this is going to a verified user or a core address | if (verifiedList[to] || coreList[to]) {
return SUCCESS_CODE;
} else {
| if (verifiedList[to] || coreList[to]) {
return SUCCESS_CODE;
} else {
| 35,874 |
121 | // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. | if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
| if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
| 4,405 |
0 | // create link amount | uint256 public totalAmount;
| uint256 public totalAmount;
| 2,950 |
105 | // Only when loan is Defaulted / | modifier onlyDefaulted() {
require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted");
_;
}
| modifier onlyDefaulted() {
require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted");
_;
}
| 40,630 |
8 | // ensure that the asset transfer request actually exists | modifier isValidTransfer(uint assetId) {
require (uint(assetsInTransfer[assetId]) != 0, "This asset was never in transfer mode"); _;
}
| modifier isValidTransfer(uint assetId) {
require (uint(assetsInTransfer[assetId]) != 0, "This asset was never in transfer mode"); _;
}
| 14,802 |
18 | // Lets someone buy a given quantity of tokens from a direct listing by paying the fixed price. _listingId The uid of the direct lisitng to buy from._buyFor The receiver of the NFT being bought._quantity The amount of NFTs to buy from the direct listing._currency The currency to pay the price in._totalPrice The total price to pay for the tokens being bought. A sale will fail to execute if either: (1) buyer does not own or has not approved Marketplace to transfer the appropriate amount of currency (or hasn't sent the appropriate amount of native tokens)(2) the lister does not own | function buy(
| function buy(
| 7,259 |
145 | // mint new tokens to address that deploys contract | _mint(msg.sender, 1000000000*10**18, "", "");
| _mint(msg.sender, 1000000000*10**18, "", "");
| 7,211 |
41 | // Disallow transfers to this contract to prevent accidental misuse. The contract should never own any kitties (except very briefly after a gen0 cat is created and before it goes on auction). | require(_to != address(this));
| require(_to != address(this));
| 33,369 |
114 | // Sets a new comptroller for the marketAdmin function to set a new comptroller return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
newComptroller; // Shh
delegateAndReturn();
}
| function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
newComptroller; // Shh
delegateAndReturn();
}
| 13,593 |
19 | // We check if the data has been verified as valid | if(isValid == 1) {
armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack;
armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense;
}
| if(isValid == 1) {
armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack;
armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense;
}
| 46,513 |
3 | // LibraryDemo & string library for Solidity contracts.This is a extended library where all the string utility finctions are added and can be inviked in the project. Functionality in this library is to count the lenght of the string / | library LibraryDemo {
/** @dev To find the length of a string passed. It will work for UTF-8 chars as well
* @param str input string
* @return length length of the string.
*/
function utfStringLength(string str)
public
pure
returns (uint length)
{
uint i = 0;
bytes memory string_rep = bytes(str);
while (i<string_rep.length)
{
if (string_rep[i]>>7==0)
i += 1;
else if (string_rep[i]>>5==0x6)
i += 2;
else if (string_rep[i]>>4==0xE)
i += 3;
else if (string_rep[i]>>3==0x1E)
i += 4;
else
//For safety
i += 1;
length++;
}
}
} | library LibraryDemo {
/** @dev To find the length of a string passed. It will work for UTF-8 chars as well
* @param str input string
* @return length length of the string.
*/
function utfStringLength(string str)
public
pure
returns (uint length)
{
uint i = 0;
bytes memory string_rep = bytes(str);
while (i<string_rep.length)
{
if (string_rep[i]>>7==0)
i += 1;
else if (string_rep[i]>>5==0x6)
i += 2;
else if (string_rep[i]>>4==0xE)
i += 3;
else if (string_rep[i]>>3==0x1E)
i += 4;
else
//For safety
i += 1;
length++;
}
}
} | 22,747 |
18 | // team mint for treasury | will it be to deployer wallet? or a different one | function teamMint() external onlyOwner {
require(totalSupply() == 0, "The team has already minted.");
_safeMint(msg.sender, 50);
}
| function teamMint() external onlyOwner {
require(totalSupply() == 0, "The team has already minted.");
_safeMint(msg.sender, 50);
}
| 8,354 |
95 | // Accumulated tokens that are directed to LP | uint256 private lpTokens = 0;
| uint256 private lpTokens = 0;
| 22,374 |
59 | // The address of official MarbleCards contract that stores the metadata about each card./The owner is not capable of changing the address of the MarbleCards Core contract/once the contract has been deployed./ Ropsten Testnet address public cardCoreAddress = 0x5bb5Ce2EAa21375407F05FcA36b0b04F115efE7d;/ Mainnet | address public cardCoreAddress = 0x1d963688FE2209A98dB35C67A041524822Cf04ff;
CardCore cardCore;
| address public cardCoreAddress = 0x1d963688FE2209A98dB35C67A041524822Cf04ff;
CardCore cardCore;
| 30,627 |
173 | // Mints some amount of tokens to an address _toAddress of the future owner of the token _idToken ID to mint _quantityAmount of tokens to mint _dataData to pass if receiver is contract / | function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
| function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
| 28,285 |
46 | // Withdraw Token.token token address.amt token amount.unitAmt unit amount of curve_amt/token_amt with slippage.getId Get token amount at this ID from `InstaMemory` Contract.setId Set token amount at this ID in `InstaMemory` Contract./ | function withdraw(
address token,
uint256 amt,
uint256 unitAmt,
uint getId,
uint setId
| function withdraw(
address token,
uint256 amt,
uint256 unitAmt,
uint getId,
uint setId
| 44,759 |
370 | // Contract Registry interface / | interface IContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
| interface IContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
| 23,687 |
14 | // Emit an event to indicate a new token creation. | emit TokenCreated(newTokenId, totalSupply, price);
| emit TokenCreated(newTokenId, totalSupply, price);
| 17,010 |
14 | // Huffman code decoding tables | struct Huffman {
uint256[] counts;
uint256[] symbols;
}
| struct Huffman {
uint256[] counts;
uint256[] symbols;
}
| 9,203 |
52 | // Closes the period in which the crowdsale is open. / | function closeCrowdsale(bool closed_) public onlyOwner {
closed = closed_;
}
| function closeCrowdsale(bool closed_) public onlyOwner {
closed = closed_;
}
| 41,999 |
153 | // if a bid has been placed, then we will have a bidding end timestamp and we need to ensure no one can bid beyond this | require(block.timestamp < originalBiddingEnd, "No longer accepting bids");
uint128 secondsUntilBiddingEnd = originalBiddingEnd - uint128(block.timestamp);
| require(block.timestamp < originalBiddingEnd, "No longer accepting bids");
uint128 secondsUntilBiddingEnd = originalBiddingEnd - uint128(block.timestamp);
| 3,856 |
61 | // - TO-DO: ADD VOTING/ERC20 extended for Boshi 'pair'. | contract BoshiERC20 is Domain, ERC20Data {
using BoshiMath for uint256;
string public constant name = 'Boshi LP Token';
string public constant symbol = 'bSLP';
uint8 public constant decimals = 18;
uint256 public totalSupply;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/// @dev Internal Boshi pair LP mint.
function _mint(address to, uint256 amount) internal {
totalSupply = totalSupply.add(amount);
balanceOf[to] = balanceOf[to].add(amount);
emit Transfer(address(0), to, amount);
}
/// @dev Internal Boshi pair LP burn.
function _burn(address from, uint256 amount) internal {
balanceOf[from] = balanceOf[from].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(from, address(0), amount);
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) external returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (msg.sender != to) {
require(to != address(0), "BoshiERC20: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "BoshiERC20: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "BoshiERC20: no zero address"); // Moved down so other failed calls save some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"ERC20: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
| contract BoshiERC20 is Domain, ERC20Data {
using BoshiMath for uint256;
string public constant name = 'Boshi LP Token';
string public constant symbol = 'bSLP';
uint8 public constant decimals = 18;
uint256 public totalSupply;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/// @dev Internal Boshi pair LP mint.
function _mint(address to, uint256 amount) internal {
totalSupply = totalSupply.add(amount);
balanceOf[to] = balanceOf[to].add(amount);
emit Transfer(address(0), to, amount);
}
/// @dev Internal Boshi pair LP burn.
function _burn(address from, uint256 amount) internal {
balanceOf[from] = balanceOf[from].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(from, address(0), amount);
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) external returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (msg.sender != to) {
require(to != address(0), "BoshiERC20: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "BoshiERC20: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "BoshiERC20: no zero address"); // Moved down so other failed calls save some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"ERC20: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
| 774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.