Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
92
// execute message from non-evm chain with bytes for sender address, otherwise same as above.
function executeMessage( bytes calldata _sender, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus);
function executeMessage( bytes calldata _sender, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus);
48,355
2
// required: the LayerZero endpoint which is passed in the constructor
ILayerZeroEndpoint public endpoint;
ILayerZeroEndpoint public endpoint;
20,866
15
// 查询条件
Condition condition = table.newCondition(); condition.EQ("name", name);
Condition condition = table.newCondition(); condition.EQ("name", name);
41,739
29
// Mints new tickets for the user and posts a message to the board. _message Message to broadcast /
function submit(string memory _message) public
function submit(string memory _message) public
34,197
145
// Load and unpack the data in the midpoint index
(uint256 pastBlock, uint256 loadedData) = _loadAndUnpack(data, mid);
(uint256 pastBlock, uint256 loadedData) = _loadAndUnpack(data, mid);
27,541
629
// Emitted when the input is less than or equal to zero.
error PRBMathSD59x18__LogInputTooSmall(int256 x);
error PRBMathSD59x18__LogInputTooSmall(int256 x);
34,031
4
// Adds two numbers, throws on overflow. /
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
264
6,194
// 3099
entry "rostroventrally" : ENG_ADVERB
entry "rostroventrally" : ENG_ADVERB
23,935
12
// GOVERNANCE FUNCTION: Batch edit adapters for modules. Reverts if module andadapter name don't map to an adapter address _modulesArray of addresses of the modules associated with integration_namesArray of human readable strings identifying the integration_adapters Array of addresses of the adapter contracts to add /
function batchEditIntegration( address[] memory _modules, string[] memory _names, address[] memory _adapters ) external onlyOwner
function batchEditIntegration( address[] memory _modules, string[] memory _names, address[] memory _adapters ) external onlyOwner
14,046
11
// SQUARES
string[2] memory parts = [ string(abi.encodePacked ( '<pattern id="moon" viewBox="0,-0.5,10,10" width="100%" height="100%"><rect width="10" height="10" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="2" transform="translate(0.05,-0.5)"/><rect width="5" height="5" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorOne],'" transform="translate(2.5,2)"/><rect width="4" height="4" stroke="black" fill="', colors[rug.colorOne],'" transform="translate(3,2.5)" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<rect width="6" height="6" stroke="black" fill="none" transform="translate(2,1.5)" stroke-width="0.3"/><circle cx="5" cy="4.5" r="1" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorThree],'"/><g stroke="black" stroke-width="0.3" fill="none"><circle cx="5" cy="4.5" r="1.5"/><circle cx="5" cy="4.5" r="0.5"/> </g></pattern><pattern id="star" viewBox="7,-0.5,7,10" width="17%" height="20%"><g fill="url(#moon)" stroke="', colors[rug.background],'"><rect width="10" height="10" transform="translate(0,-0.5)"/><rect width="10" height="10" transform="translate(10,4.5)"/><rect width="10" height="10" transform="translate(10,-5.5)"/></g><animate attributeName="x" from="0" to="0.17" dur="1.43s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke-width="3" stroke="black"/>' )) ];
string[2] memory parts = [ string(abi.encodePacked ( '<pattern id="moon" viewBox="0,-0.5,10,10" width="100%" height="100%"><rect width="10" height="10" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="2" transform="translate(0.05,-0.5)"/><rect width="5" height="5" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorOne],'" transform="translate(2.5,2)"/><rect width="4" height="4" stroke="black" fill="', colors[rug.colorOne],'" transform="translate(3,2.5)" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<rect width="6" height="6" stroke="black" fill="none" transform="translate(2,1.5)" stroke-width="0.3"/><circle cx="5" cy="4.5" r="1" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorThree],'"/><g stroke="black" stroke-width="0.3" fill="none"><circle cx="5" cy="4.5" r="1.5"/><circle cx="5" cy="4.5" r="0.5"/> </g></pattern><pattern id="star" viewBox="7,-0.5,7,10" width="17%" height="20%"><g fill="url(#moon)" stroke="', colors[rug.background],'"><rect width="10" height="10" transform="translate(0,-0.5)"/><rect width="10" height="10" transform="translate(10,4.5)"/><rect width="10" height="10" transform="translate(10,-5.5)"/></g><animate attributeName="x" from="0" to="0.17" dur="1.43s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke-width="3" stroke="black"/>' )) ];
54,658
23
// Emitted when sale is created/saleList contains the details of sale created/CreatedOrUpdated the details provide whether sale is created or updated
event saleCreated(PriceList saleList, string CreatedOrUpdated);
event saleCreated(PriceList saleList, string CreatedOrUpdated);
6,487
47
// return true if the ICO is in pre ICO phase
function isPreIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPreIco = PayableStages.PreIco == getPayableStage(); return isPayable && isPreIco; }
function isPreIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPreIco = PayableStages.PreIco == getPayableStage(); return isPayable && isPreIco; }
26,857
132
// Compound's CToken this BToken contract is tied to
address public cToken;
address public cToken;
16,673
2
// Airdrop Helper for Camel Clans/metacrypt.org
contract CamelAirdrop is AirdropHelper, ContractSafe { function isTargetContract(address target) public view returns (bool) { return ContractSafe.isContract(target); } function isTargetsContract(address[] memory targets) public view returns (bool[] memory _res) { _res = new bool[](targets.length); for (uint256 i = 0; i < targets.length; i++) { _res[i] = isTargetContract(targets[i]); } } }
contract CamelAirdrop is AirdropHelper, ContractSafe { function isTargetContract(address target) public view returns (bool) { return ContractSafe.isContract(target); } function isTargetsContract(address[] memory targets) public view returns (bool[] memory _res) { _res = new bool[](targets.length); for (uint256 i = 0; i < targets.length; i++) { _res[i] = isTargetContract(targets[i]); } } }
40,637
186
// revoke entries for liquidations (access controlled to Synthetix)
function revokeFrom( address account, address recipient, uint targetAmount, uint startIndex ) external;
function revokeFrom( address account, address recipient, uint targetAmount, uint startIndex ) external;
40,872
18
// to-do : set time lock or is inactive for finish period withdraw
investers[sender].lock_time = block.timestamp + confirmTime; investers[sender].refundCounter++; emit depositRefundEvent(sender, amount);
investers[sender].lock_time = block.timestamp + confirmTime; investers[sender].refundCounter++; emit depositRefundEvent(sender, amount);
32,764
89
// Internal function to safely mint a new token.Reverts if the given token ID already exists.If the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,the transfer is reverted. to The address that will own the minted token tokenId uint256 ID of the token to be minted _data bytes data to send along with a safe transfer check /
function _safeMint( address to, uint256 tokenId, bytes memory _data
function _safeMint( address to, uint256 tokenId, bytes memory _data
6,039
429
// Constructor. requires end period to be larger than start periodSets local period parameters and sets isActive to false _periodStart The time from when the contract can be started _periodEnd The time from when the contract can be ended _avatar DAO avatar /
constructor( uint256 _periodStart, uint256 _periodEnd, Avatar _avatar
constructor( uint256 _periodStart, uint256 _periodEnd, Avatar _avatar
49,602
7
// Returns the price of a price feed without any sanity checks./This function returns the most recent price update in this contract without any recency checks./ This function is unsafe as the returned price update may be arbitrarily far in the past.// Users of this function should check the `publishTime` in the price to ensure that the returned price is/ sufficiently recent for their application. If you are considering using this function, it may be/ safer / easier to use either `getPrice` or `getPriceNoOlderThan`./ return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
5,806
25
// principalBalanceOf returns the balance of principal token which yield a reward share for this account.
function principalBalanceOf(address _account) public view returns (uint256) { return debtValueOf(_account); }
function principalBalanceOf(address _account) public view returns (uint256) { return debtValueOf(_account); }
22,645
6
// Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} iscalled. NOTE: This information is only used for _display_ purposes: it inno way affects any of the arithmetic of the contract, including{IERC20-balanceOf} and {IERC20-transfer}. /
function decimals() public view returns (uint8) { return _decimals; }
function decimals() public view returns (uint8) { return _decimals; }
20,178
9
// Opens a new position in the Beta smart contract.
function open( address _owner, address _underlying, address _collateral ) external returns (uint pid);
function open( address _owner, address _underlying, address _collateral ) external returns (uint pid);
38,900
16
// Provides methods to safely add, subtract and multiply uint256 numbers. /
contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } }
contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } }
28,730
139
// As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address");
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address");
24,984
35
// string memory _dateFilled, uint256 _dateRxEnd, string memory _dateNextFill, uint256 _dateRxNext
)
)
1,491
1
// Constructor, creates AutoRefundVault. /
function AutoRefundableCrowdsale() public { vault = new AutoRefundVault(wallet); }
function AutoRefundableCrowdsale() public { vault = new AutoRefundVault(wallet); }
32,558
314
// Partial interface for a SushiSwap Router contract /
interface ISushiSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); }
interface ISushiSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); }
43,844
1
// Emitted when a contract's basic mint configuration is updated./_contract The address of the contract being configured./_config The new configuration.
event ConfigurationUpdated(address indexed _contract, BasicMintConfiguration _config);
event ConfigurationUpdated(address indexed _contract, BasicMintConfiguration _config);
9,823
71
// buyBackTokens(balance.div(100));
32,659
3
// L1 FRAX -> anyFRAX Simple dump in / CREATE2 AnySwap Bridge
TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount);
TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount);
36,308
7
// function can(address, address) external view returns (uint);
function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint);
function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint);
23,716
178
// Destroys 'tokenId'.The approval is cleared when the token is burned. Requirements: - 'tokenId' must exist.
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
26,195
38
// HARDCODED FOR Ethereum MainnetCOORDINATOR: 0x271682DEB8C4E0901D1a1550aD2e64D568E69909 /
constructor( uint64 subscriptionId, address _upkeep, address _sendIt, address _pool, uint256 _totalSupply ) VRFConsumerBaseV2(0x271682DEB8C4E0901D1a1550aD2e64D568E69909)
constructor( uint64 subscriptionId, address _upkeep, address _sendIt, address _pool, uint256 _totalSupply ) VRFConsumerBaseV2(0x271682DEB8C4E0901D1a1550aD2e64D568E69909)
36,884
6
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; }
struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; }
8,486
20
// Balance ledgerpersonal factorglobalFactor / constantFactor
return balanceLedger_[_customerAddress].mul(personalFactorLedger_[_customerAddress]).mul(globalFactor) / constantFactor;
return balanceLedger_[_customerAddress].mul(personalFactorLedger_[_customerAddress]).mul(globalFactor) / constantFactor;
21,111
31
// Generic purchase function for GNXTokens. General purchase function for exchanging GNXNative for GNXTokens.minTokens Minimum number of tokens expected from output.nativeSold Quantity of GNXNative sold. return Quantity of GNXTokens output.
function buyTokens(uint256 minTokens, uint256 nativeSold) public override(IGNXPool) returns (uint256) { // Checks if user has enough GNXNative to sell require(native.balanceOf(msg.sender) >= nativeSold,"GNX: not enough GNXNative"); uint256 tokenOutput = _buyTokens(minTokens, nativeSold, msg.sender); return tokenOutput; }
function buyTokens(uint256 minTokens, uint256 nativeSold) public override(IGNXPool) returns (uint256) { // Checks if user has enough GNXNative to sell require(native.balanceOf(msg.sender) >= nativeSold,"GNX: not enough GNXNative"); uint256 tokenOutput = _buyTokens(minTokens, nativeSold, msg.sender); return tokenOutput; }
7,484
17
// These functions deal with verification of Merkle trees (hash trees), /
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] calldata proof, bytes32 leaf, bytes32 root) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } }
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] calldata proof, bytes32 leaf, bytes32 root) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } }
894
8
// No Parent exist, root node
if(evInfo & 8192 == 8192)
if(evInfo & 8192 == 8192)
22,728
6
// The address of the DAO token
DaotInterface public daot;
DaotInterface public daot;
24,341
6
// returns the G2 generator/mind the ordering of the 1s and 0s!/this is because of the (unknown to us) convention used in the bn254 pairing precompile contract/"Elements ai + b of F_p^2 are encoded as two elements of F_p, (a, b)."/https:github.com/ethereum/EIPs/blob/master/EIPS/eip-197.mdencoding
function generatorG2() internal pure returns (G2Point memory) { return G2Point( [G2x1, G2x0], [G2y1, G2y0] ); }
function generatorG2() internal pure returns (G2Point memory) { return G2Point( [G2x1, G2x0], [G2y1, G2y0] ); }
38,529
54
// Crowdsale Start time has been changed
event StartsAtChanged(uint startsAt);
event StartsAtChanged(uint startsAt);
35,404
154
// counter for the farming setup info
uint256 public _farmingSetupsInfoCount;
uint256 public _farmingSetupsInfoCount;
24,961
4
// Enumerate NFTs assigned to an owner/Throws if `_index` >= `balanceOf(_owner)` or if/`_owner` is the zero address, representing invalid NFTs./_owner An address where we are interested in NFTs owned by them/_index A counter less than `balanceOf(_owner)`/ return The token identifier for the `_index`th NFT assigned to `_owner`,/ (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256){ require(_index < balances[_owner]); return ownerTokenIndexes[_owner][_index]; }
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256){ require(_index < balances[_owner]); return ownerTokenIndexes[_owner][_index]; }
15,775
27
// Save a reference to the delegate to use.
IJBPayDelegate _delegate;
IJBPayDelegate _delegate;
9,481
9
// Returns the gauge's relative weight for a given time, capped to its relative weight cap attribute. time Timestamp in the past or present. /
function getCappedRelativeWeight(uint256 time) external view returns (uint256);
function getCappedRelativeWeight(uint256 time) external view returns (uint256);
21,264
45
// - each app level can at least "relay" the same amount of input flow rate to others - each app level get a same amount of allowance
if (optype == FlowChangeType.CREATE_FLOW) { cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP; } else if (optype == FlowChangeType.UPDATE_FLOW) {
if (optype == FlowChangeType.CREATE_FLOW) { cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP; } else if (optype == FlowChangeType.UPDATE_FLOW) {
10,498
55
// Checks if Crowdfund Contract is performing the action /
modifier onlyCrowdfundContract()
modifier onlyCrowdfundContract()
7,415
23
// Internal function that mints an amount of the token and assigns it toan account. This encapsulates the modification of balances such that theproper events are emitted. _account The account that will receive the created tokens. _amount The amount that will be created. /
function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); }
function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); }
44,285
35
// _purchasedReservations.push(res.id);
_pendingPool += res.cost; if(res.cost < msg.value) { msg.sender.transfer(msg.value - res.cost); }
_pendingPool += res.cost; if(res.cost < msg.value) { msg.sender.transfer(msg.value - res.cost); }
19,180
49
// require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount);
require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount);
11,503
31
// INTERNAL: attempts to transfer part of the contract balance to the caller, provided the account is a shareholder andon the basis of its shares and previous withdrawals._account the address of the shareholder to pay out /
function _withdraw(address payable _account) internal { uint256 _amount = this.withdrawable(_account); require(_amount != 0, "Account is not due payment"); withdrawals[_account] += _amount; withdrawn += _amount; AddressUpgradeable.sendValue(_account, _amount); emit SharesPaid(_account, _amount); }
function _withdraw(address payable _account) internal { uint256 _amount = this.withdrawable(_account); require(_amount != 0, "Account is not due payment"); withdrawals[_account] += _amount; withdrawn += _amount; AddressUpgradeable.sendValue(_account, _amount); emit SharesPaid(_account, _amount); }
40,931
92
// left sibling
node = keccak256(abi.encodePacked(siblings[i], node));
node = keccak256(abi.encodePacked(siblings[i], node));
35,021
15
// pool index => swapped amount of token0
mapping(uint => uint) public swappedAmount0P;
mapping(uint => uint) public swappedAmount0P;
81,080
32
// SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself
contract Transferrable { using SafeERC20 for ERC20; /// @dev This function is used to move tokens sent accidentally to this contract method. /// @dev The owner can chose the new destination address /// @param _to is the recipient's address. /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @param _amount is the amount to be transferred in base units. function _safeTransfer(address payable _to, address _asset, uint _amount) internal { // address(0) is used to denote ETH if (_asset == address(0)) { _to.transfer(_amount); } else { ERC20(_asset).safeTransfer(_to, _amount); } } }
contract Transferrable { using SafeERC20 for ERC20; /// @dev This function is used to move tokens sent accidentally to this contract method. /// @dev The owner can chose the new destination address /// @param _to is the recipient's address. /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @param _amount is the amount to be transferred in base units. function _safeTransfer(address payable _to, address _asset, uint _amount) internal { // address(0) is used to denote ETH if (_asset == address(0)) { _to.transfer(_amount); } else { ERC20(_asset).safeTransfer(_to, _amount); } } }
18,765
86
// Update stabilisation fee (multiplied by DENOMINATOR) and calculate global stabilisation fee per USD up to current timestamp using previous stabilisation fee/stabilisationFeeRateD_ New stabilisation fee multiplied by DENOMINATOR
function updateStabilisationFeeRate(uint256 stabilisationFeeRateD_) external onlyVaultAdmin { if (stabilisationFeeRateD_ > DENOMINATOR) { revert InvalidValue(); } uint256 delta = block.timestamp - globalStabilisationFeePerUSDSnapshotTimestamp; globalStabilisationFeePerUSDSnapshotD += (delta * stabilisationFeeRateD) / YEAR; stabilisationFeeRateD = stabilisationFeeRateD_; globalStabilisationFeePerUSDSnapshotTimestamp = block.timestamp; emit StabilisationFeeUpdated(tx.origin, msg.sender, stabilisationFeeRateD_); }
function updateStabilisationFeeRate(uint256 stabilisationFeeRateD_) external onlyVaultAdmin { if (stabilisationFeeRateD_ > DENOMINATOR) { revert InvalidValue(); } uint256 delta = block.timestamp - globalStabilisationFeePerUSDSnapshotTimestamp; globalStabilisationFeePerUSDSnapshotD += (delta * stabilisationFeeRateD) / YEAR; stabilisationFeeRateD = stabilisationFeeRateD_; globalStabilisationFeePerUSDSnapshotTimestamp = block.timestamp; emit StabilisationFeeUpdated(tx.origin, msg.sender, stabilisationFeeRateD_); }
9,980
7
// Execute worker strategy. Take LP tokens. Return LP tokens + BaseToken./ However, some BaseToken will be deducted to pay the debt/user User address to withdraw liquidity./debt Debt amount in WAD of the user./data Extra calldata information passed along to this strategy.
function execute(address user, uint256 debt, bytes calldata data) external override payable nonReentrant { // 1. Find out what farming token we are dealing with. ( address baseToken, address farmingToken, uint256 minFarmingToken ) = abi.decode(data, (address, address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(farmingToken, baseToken)); // 2. Remove all liquidity back to BaseToken and farming tokens. lpToken.approve(address(router), uint256(-1)); router.removeLiquidity(baseToken, farmingToken, lpToken.balanceOf(address(this)), 0, 0, address(this), now); // 3. Convert farming tokens to BaseToken. address[] memory path = new address[](2); path[0] = farmingToken; path[1] = baseToken; farmingToken.safeApprove(address(router), 0); farmingToken.safeApprove(address(router), uint256(-1)); baseToken.safeApprove(address(router), 0); baseToken.safeApprove(address(router), uint256(-1)); uint256 balance = baseToken.myBalance(); if (debt > balance) { // Convert some farming tokens to BaseToken. uint256 remainingDebt = debt.sub(balance); router.swapTokensForExactTokens(remainingDebt, farmingToken.myBalance(), path, address(this), now); } // 4. Return BaseToken back to the original caller. uint256 remainingBalance = baseToken.myBalance(); baseToken.safeTransfer(msg.sender, remainingBalance); // 5. Return remaining farming tokens to user. uint256 remainingFarmingToken = farmingToken.myBalance(); require(remainingFarmingToken >= minFarmingToken, "insufficient quote tokens received"); if (remainingFarmingToken > 0) { farmingToken.safeTransfer(user, remainingFarmingToken); } }
function execute(address user, uint256 debt, bytes calldata data) external override payable nonReentrant { // 1. Find out what farming token we are dealing with. ( address baseToken, address farmingToken, uint256 minFarmingToken ) = abi.decode(data, (address, address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(farmingToken, baseToken)); // 2. Remove all liquidity back to BaseToken and farming tokens. lpToken.approve(address(router), uint256(-1)); router.removeLiquidity(baseToken, farmingToken, lpToken.balanceOf(address(this)), 0, 0, address(this), now); // 3. Convert farming tokens to BaseToken. address[] memory path = new address[](2); path[0] = farmingToken; path[1] = baseToken; farmingToken.safeApprove(address(router), 0); farmingToken.safeApprove(address(router), uint256(-1)); baseToken.safeApprove(address(router), 0); baseToken.safeApprove(address(router), uint256(-1)); uint256 balance = baseToken.myBalance(); if (debt > balance) { // Convert some farming tokens to BaseToken. uint256 remainingDebt = debt.sub(balance); router.swapTokensForExactTokens(remainingDebt, farmingToken.myBalance(), path, address(this), now); } // 4. Return BaseToken back to the original caller. uint256 remainingBalance = baseToken.myBalance(); baseToken.safeTransfer(msg.sender, remainingBalance); // 5. Return remaining farming tokens to user. uint256 remainingFarmingToken = farmingToken.myBalance(); require(remainingFarmingToken >= minFarmingToken, "insufficient quote tokens received"); if (remainingFarmingToken > 0) { farmingToken.safeTransfer(user, remainingFarmingToken); } }
16,505
7
// Resumes operational state. /
function resume() public virtual whenPaused onlyOwner { _paused = false; emit Resumed(msg.sender); }
function resume() public virtual whenPaused onlyOwner { _paused = false; emit Resumed(msg.sender); }
17,905
46
// Release all vested tokens
_releaseTo(beneficiary);
_releaseTo(beneficiary);
30,851
41
// raised when trying to set an invalid taxBPS
error InvalidTaxBPS(uint256 bps);
error InvalidTaxBPS(uint256 bps);
31,051
31
// protocol_earnings_deducted = 0-(pyth_update_feemaker.num_legs); protocol_earnings_by_asset[maker.collateral] += payout .protocol_profit; protocol_profit = payout.protocol_profit;
protocol_profit = payout.protocol_profit;
protocol_profit = payout.protocol_profit;
30,447
142
// Cancels an outstanding Chainlink request.The oracle contract requires the request ID and additional metadata tovalidate the cancellation. Only old answers can be cancelled. _requestId is the identifier for the chainlink request being cancelled _payment is the amount of LINK paid to the oracle for the request _expiration is the time when the request expires /
function cancelRequest( bytes32 _requestId, uint256 _payment, uint256 _expiration ) external ensureAuthorizedRequester()
function cancelRequest( bytes32 _requestId, uint256 _payment, uint256 _expiration ) external ensureAuthorizedRequester()
30,986
89
// Allow AMFEIX to transfer AMF to claiming users tokenAmount Amount of tokens to be sent userAddress BTC address on which users willing to receive payment btcTxId ID of the AMF buying transaction on Bitcoin network /
function payAMF(uint256 tokenAmount, address userAddress, string memory btcTxId) public virtual returns (bool) { require(_msgSender() == _tokenPool, "Only AMFEIX can use this method"); _transfer(_msgSender(), userAddress, tokenAmount); emit AmfPaid(userAddress, btcTxId, tokenAmount); return true; }
function payAMF(uint256 tokenAmount, address userAddress, string memory btcTxId) public virtual returns (bool) { require(_msgSender() == _tokenPool, "Only AMFEIX can use this method"); _transfer(_msgSender(), userAddress, tokenAmount); emit AmfPaid(userAddress, btcTxId, tokenAmount); return true; }
54,337
4
// Info used to describe a status./status Status of the stake./poolId Unique Id of pool. This is set when status=DELEGATED.
struct StakeInfo { StakeStatus status; bytes32 poolId; }
struct StakeInfo { StakeStatus status; bytes32 poolId; }
28,090
5
// The version of this contract
string private constant VERSION = '1';
string private constant VERSION = '1';
38,386
131
// Added by Huwei
uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres); return (
uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres); return (
55,735
155
// Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call)./Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard)./ MUST revert if `_to` is the zero address./ MUST revert if balance of holder for token `_id` is lower than the `_value` sent./ MUST revert on any other error./ MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard)./ After the above conditions are met, this function MUST check if `_to` is a smart
function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data ) external;
function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data ) external;
23,276
104
// sliding window oracle that uses observations collected over a window to provide moving price averages in the past `windowSize` with a precision of `windowSize / granularity` note this is a singleton oracle and only needs to be deployed once per desired parameters, which differs from the simple oracle which must be deployed once per pair.
contract GenesisOracle is Ownable,GenesisOracleData { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0; uint price0Cumulative; } // the desired amount of time over which the moving average should be computed, e.g. 24 hours uint256 public windowSize = 86400;//one day // the number of observations stored for each pair, i.e. how many price observations are stored for the window. // as granularity increases from 1, more frequent updates are needed, but moving averages become more precise. // averages are computed over intervals with sizes in the range: // [windowSize - (windowSize / granularity) * 2, windowSize] // e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for // the period: // [now - [22 hours, 24 hours], now] uint256 public granularity = 24;//24 times // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint256 public periodSize = windowSize/ granularity; address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //address public susiFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; address public susiFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;//use uni address public uniWbtcUsdtLp = 0x004375Dff511095CC5A197A54140a24eFEF3A416;//lp address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;//wbtc //address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;//usdt address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;//usdc address public btch = address(0);//btch // address public susiWbtcUsdtLp = 0x784178D58b641a4FebF8D477a6ABd28504273132;//lp address public susiBtchWbtcLp = address(0); uint256 public btcDecimal = 1e8; uint256 public usdcDecimal = 1e6; uint256 public btchDecimal = 1e9; uint256 public priceDecimal = 1e8; uint256 public daySeconds = 86400; uint256 public lastUpdateTime; //tokenAddress=>dayIdx(timeStamp/86400)=>price //WBTC/USDT, BTCH/WBTC两种币对, //WBTC/USDT需要365,24,实时, UNI //BTCH/WBTC需要24, 实时,SUSHI mapping(uint256=>uint256) public sushiBtchDayPrice; // mapping(uint256=>uint256) public uiniAvgBtcDayPrice; mapping(uint256=>uint256) public uiniAvgBtcDayCumulativePrice; mapping(address =>mapping(uint256=>Observation)) public pairObservations; event SetBtcAvg24Price(address indexed from,uint256 avgPrice,uint256 periodIdx); event BtchAvg24Price(address indexed from,uint256 avgPrice,uint256 periodIdx); constructor() public { uint256 idx = btcDaySartTime/daySeconds; for(uint256 i=0;i<btcCumulativePrice.length;i++){ uiniAvgBtcDayCumulativePrice[idx++] = btcCumulativePrice[i]; } } function setTimeWndGranularity(uint windowSize_, uint8 granularity_) external onlyOwner { require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY'); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, 'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE' ); windowSize = windowSize_; granularity = granularity_; } function setFactoryAddress(address uniFactory_,address susiFactory_) external onlyOwner{ uniFactory = uniFactory_; susiFactory = susiFactory_; } function initBtch(address btch_,uint256 btchDecimal_) external onlyOwner{ btch = btch_; btchDecimal = btchDecimal_; } function setBtc(address wbtc_,uint256 btcDecimal_) external onlyOwner{ wbtc = wbtc_; btcDecimal = btcDecimal_; } function setUsdc(address usdc_,uint256 usdcDecimal_) external onlyOwner{ usdc = usdc_; usdcDecimal = usdcDecimal_; } function setBtcCumulativeDayPrice(uint256[] calldata _timestamps,uint256[] calldata _btcCumulativePrice) external onlyOwner { require(_timestamps.length== _btcCumulativePrice.length,"array length is not equal!"); for(uint256 i=0;i<_timestamps.length;i++){ uint256 dayidx = _timestamps[i]/daySeconds; uiniAvgBtcDayCumulativePrice[dayidx] = _btcCumulativePrice[i]; } } function btchSetCumulativeDayPrice(uint256[] calldata _timestamps,uint256[] calldata _btchDayCumulativeprices) external onlyOwner{ require(_timestamps.length== _btchDayCumulativeprices.length,"array length is not equal!"); for(uint256 i=0;i< _timestamps.length;i++) { uint256 dayidx = _timestamps[i]/daySeconds; sushiBtchDayPrice[dayidx] = _btchDayCumulativeprices[i]; } } function setBtcCumOberverVationData(uint256[] calldata _timestamps,uint256[] calldata _data) external onlyOwner { require(_timestamps.length==_data.length,"array length is not equal"); uint256 idx = 0; for(uint256 i=0;i<_timestamps.length;i++) { idx = _timestamps[i]/periodSize; pairObservations[wbtc][idx] = Observation(block.timestamp,0,_data[i]); } } function btchSetCumOberverVationData(uint256[] calldata _timestamps,uint256[] calldata _data) external onlyOwner { require(_timestamps.length==_data.length,"array length is not equal"); uint256 idx = 0; for(uint256 i=0;i<_timestamps.length;i++) { idx = _timestamps[i]/periodSize; pairObservations[btch][idx] = Observation(block.timestamp,0,_data[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////// function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) internal pure returns (uint amountOut) { if(timeElapsed==0) { return 0; } // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } //eAvgPrice(susiFactory,btch,btchDecimal,priceStart,priceEnd,startTime,endTime,wbtc); //getTimeAvgPrice(susiFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); function getTimeAvgPrice(address factory, address tokenIn, uint amountIn, uint priceInCumulativeStart, uint priceInCumulativeEnd, uint startTime, uint endTime, address tokenOut) internal view returns (uint amountOut) { if(startTime==0||endTime==0||startTime>=block.timestamp ||priceInCumulativeStart>priceInCumulativeEnd) { return 0; } address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); uint timeElapsed = block.timestamp.sub(startTime); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if(price0Cumulative<priceInCumulativeEnd) { price0Cumulative = priceInCumulativeEnd; timeElapsed = endTime.sub(startTime); } return computeAmountOut(priceInCumulativeStart, price0Cumulative, timeElapsed, amountIn); } //btch realtime price in wbtc function getBTCHBTC() public view returns(uint256){ if(btch==address(0)||wbtc==address(0)) { return 0; } (uint256 btchReserve/*reserveA*/,uint256 wbtcReserve/*reserveB*/)= UniswapV2Library.getReserves(susiFactory, btch/*tokenA*/, wbtc/*tokenB*/); if(btchReserve==0) { return 0; } return UniswapV2Library.quote(btchDecimal,btchReserve,wbtcReserve); } //btch avg price(24 hours) in wbtc function getBTCHBTC24() public view returns(uint256){ if(btch==address(0)) { return 0; } uint256 idx = block.timestamp/periodSize; uint256 i = idx - daySeconds/periodSize; uint startTime = pairObservations[btch][i].timestamp; uint priceStart = pairObservations[btch][i].price0Cumulative; if(priceStart==0) { for(;i<idx;i++) { priceStart = pairObservations[btch][i].price0Cumulative; if(priceStart>0) { startTime = pairObservations[btch][i].timestamp; break; } } } uint priceEnd = pairObservations[btch][idx].price0Cumulative; uint j=idx; uint endTime = pairObservations[btch][j].timestamp; if(priceEnd==0) { for(;j>i;j--) { priceEnd = pairObservations[btch][j].price0Cumulative; if(priceEnd>0) { endTime = pairObservations[btch][j].timestamp; break; } } } uint timeAvgPrice = getTimeAvgPrice(susiFactory,btch,btchDecimal,priceStart,priceEnd,startTime,endTime,wbtc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCHBTC(); } //btch realtime price in wbtc function getBTCUSDC() public view returns(uint256){ if(wbtc==address(0)||usdc==address(0)) { return 0; } (uint256 btcReserve/*reserveA*/,uint256 usdcReserve/*reserveB*/)= UniswapV2Library.getReserves(uniFactory, wbtc/*tokenA*/, usdc/*tokenB*/); if(btcReserve==0) { return 0; } return UniswapV2Library.quote(btcDecimal,btcReserve,usdcReserve); } //btc avg price(24 hours) in wbtc function getBTCUSDC24() public view returns(uint256){ if(wbtc==address(0)) { return 0; } uint256 idx = block.timestamp/periodSize; uint256 i = idx - daySeconds/periodSize; uint priceStart = pairObservations[wbtc][i].price0Cumulative; uint startTime = pairObservations[wbtc][i].timestamp; if(priceStart==0) { for(;i<idx;i++) { priceStart = pairObservations[wbtc][i].price0Cumulative; if(priceStart>0) { startTime = pairObservations[wbtc][i].timestamp; break; } } } uint priceEnd = pairObservations[wbtc][idx].price0Cumulative; uint j=idx; uint endTime = pairObservations[wbtc][j].timestamp; if(priceEnd==0) { for(;j>i;j--) { priceEnd = pairObservations[wbtc][j].price0Cumulative; if(priceEnd>0) { endTime = pairObservations[wbtc][j].timestamp; break; } } } uint timeAvgPrice = getTimeAvgPrice(uniFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCUSDC(); } function getBTCUSDC365() external view returns(uint256) { uint256 dayidx = block.timestamp/daySeconds; uint256 startIdx = dayidx -365; uint startTime = startIdx*daySeconds; uint priceStart = uiniAvgBtcDayCumulativePrice[startIdx]; if(priceStart==0) { for(;startIdx<dayidx;startIdx++) { priceStart = uiniAvgBtcDayCumulativePrice[startIdx]; if(priceStart>0) { startTime = startIdx*daySeconds; break; } } } uint priceEnd = uiniAvgBtcDayCumulativePrice[dayidx]; uint j=dayidx; uint endTime = j*daySeconds; if(priceEnd==0) { for(;j>startIdx;j--) { priceEnd = uiniAvgBtcDayCumulativePrice[j]; if(priceEnd>0) { endTime = j*daySeconds; break; } } } uint timeAvgPrice = getTimeAvgPrice(uniFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCUSDC24(); } function needUpdate() public view returns (bool) { uint256 idx = block.timestamp/periodSize; bool timeupdate = (block.timestamp-lastUpdateTime)>(periodSize/2); bool uniupdate = (pairObservations[wbtc][idx].timestamp==0); bool susiupdate = (pairObservations[btch][idx].timestamp==0); return (uniupdate&&susiupdate&&timeupdate); } function update() external { //will return if is not over periodSize/2 if((block.timestamp-lastUpdateTime)<(periodSize/2)) { return; } //update observation for uni btc day price updateOberverVation(); lastUpdateTime = block.timestamp; } // update the cumulative price for the observation at the current timestamp. each observation is updated at most // once per epoch period. function updateOberverVation() private { uint256 idx = block.timestamp/periodSize; uint256 price = 0; if(wbtc!=address(0)) { if(pairObservations[wbtc][idx].timestamp==0) { address pair = UniswapV2Library.pairFor(uniFactory,wbtc,usdc); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); price = getBTCUSDC(); pairObservations[wbtc][idx] = Observation(block.timestamp,price,price0Cumulative); //record day price0Cumulative uint256 dayidx = block.timestamp/daySeconds; if(uiniAvgBtcDayCumulativePrice[dayidx]==0) { uiniAvgBtcDayCumulativePrice[dayidx]=price0Cumulative; } emit SetBtcAvg24Price(msg.sender,price,idx); } } if(btch!=address(0)) { if(pairObservations[btch][idx].timestamp==0) { address pair = UniswapV2Library.pairFor(susiFactory,btch,wbtc); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); price = getBTCHBTC(); pairObservations[btch][idx] = Observation(block.timestamp,price,price0Cumulative); emit BtchAvg24Price(msg.sender,price,idx); } } } }
contract GenesisOracle is Ownable,GenesisOracleData { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0; uint price0Cumulative; } // the desired amount of time over which the moving average should be computed, e.g. 24 hours uint256 public windowSize = 86400;//one day // the number of observations stored for each pair, i.e. how many price observations are stored for the window. // as granularity increases from 1, more frequent updates are needed, but moving averages become more precise. // averages are computed over intervals with sizes in the range: // [windowSize - (windowSize / granularity) * 2, windowSize] // e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for // the period: // [now - [22 hours, 24 hours], now] uint256 public granularity = 24;//24 times // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint256 public periodSize = windowSize/ granularity; address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //address public susiFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; address public susiFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;//use uni address public uniWbtcUsdtLp = 0x004375Dff511095CC5A197A54140a24eFEF3A416;//lp address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;//wbtc //address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;//usdt address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;//usdc address public btch = address(0);//btch // address public susiWbtcUsdtLp = 0x784178D58b641a4FebF8D477a6ABd28504273132;//lp address public susiBtchWbtcLp = address(0); uint256 public btcDecimal = 1e8; uint256 public usdcDecimal = 1e6; uint256 public btchDecimal = 1e9; uint256 public priceDecimal = 1e8; uint256 public daySeconds = 86400; uint256 public lastUpdateTime; //tokenAddress=>dayIdx(timeStamp/86400)=>price //WBTC/USDT, BTCH/WBTC两种币对, //WBTC/USDT需要365,24,实时, UNI //BTCH/WBTC需要24, 实时,SUSHI mapping(uint256=>uint256) public sushiBtchDayPrice; // mapping(uint256=>uint256) public uiniAvgBtcDayPrice; mapping(uint256=>uint256) public uiniAvgBtcDayCumulativePrice; mapping(address =>mapping(uint256=>Observation)) public pairObservations; event SetBtcAvg24Price(address indexed from,uint256 avgPrice,uint256 periodIdx); event BtchAvg24Price(address indexed from,uint256 avgPrice,uint256 periodIdx); constructor() public { uint256 idx = btcDaySartTime/daySeconds; for(uint256 i=0;i<btcCumulativePrice.length;i++){ uiniAvgBtcDayCumulativePrice[idx++] = btcCumulativePrice[i]; } } function setTimeWndGranularity(uint windowSize_, uint8 granularity_) external onlyOwner { require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY'); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, 'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE' ); windowSize = windowSize_; granularity = granularity_; } function setFactoryAddress(address uniFactory_,address susiFactory_) external onlyOwner{ uniFactory = uniFactory_; susiFactory = susiFactory_; } function initBtch(address btch_,uint256 btchDecimal_) external onlyOwner{ btch = btch_; btchDecimal = btchDecimal_; } function setBtc(address wbtc_,uint256 btcDecimal_) external onlyOwner{ wbtc = wbtc_; btcDecimal = btcDecimal_; } function setUsdc(address usdc_,uint256 usdcDecimal_) external onlyOwner{ usdc = usdc_; usdcDecimal = usdcDecimal_; } function setBtcCumulativeDayPrice(uint256[] calldata _timestamps,uint256[] calldata _btcCumulativePrice) external onlyOwner { require(_timestamps.length== _btcCumulativePrice.length,"array length is not equal!"); for(uint256 i=0;i<_timestamps.length;i++){ uint256 dayidx = _timestamps[i]/daySeconds; uiniAvgBtcDayCumulativePrice[dayidx] = _btcCumulativePrice[i]; } } function btchSetCumulativeDayPrice(uint256[] calldata _timestamps,uint256[] calldata _btchDayCumulativeprices) external onlyOwner{ require(_timestamps.length== _btchDayCumulativeprices.length,"array length is not equal!"); for(uint256 i=0;i< _timestamps.length;i++) { uint256 dayidx = _timestamps[i]/daySeconds; sushiBtchDayPrice[dayidx] = _btchDayCumulativeprices[i]; } } function setBtcCumOberverVationData(uint256[] calldata _timestamps,uint256[] calldata _data) external onlyOwner { require(_timestamps.length==_data.length,"array length is not equal"); uint256 idx = 0; for(uint256 i=0;i<_timestamps.length;i++) { idx = _timestamps[i]/periodSize; pairObservations[wbtc][idx] = Observation(block.timestamp,0,_data[i]); } } function btchSetCumOberverVationData(uint256[] calldata _timestamps,uint256[] calldata _data) external onlyOwner { require(_timestamps.length==_data.length,"array length is not equal"); uint256 idx = 0; for(uint256 i=0;i<_timestamps.length;i++) { idx = _timestamps[i]/periodSize; pairObservations[btch][idx] = Observation(block.timestamp,0,_data[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////// function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) internal pure returns (uint amountOut) { if(timeElapsed==0) { return 0; } // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } //eAvgPrice(susiFactory,btch,btchDecimal,priceStart,priceEnd,startTime,endTime,wbtc); //getTimeAvgPrice(susiFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); function getTimeAvgPrice(address factory, address tokenIn, uint amountIn, uint priceInCumulativeStart, uint priceInCumulativeEnd, uint startTime, uint endTime, address tokenOut) internal view returns (uint amountOut) { if(startTime==0||endTime==0||startTime>=block.timestamp ||priceInCumulativeStart>priceInCumulativeEnd) { return 0; } address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); uint timeElapsed = block.timestamp.sub(startTime); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if(price0Cumulative<priceInCumulativeEnd) { price0Cumulative = priceInCumulativeEnd; timeElapsed = endTime.sub(startTime); } return computeAmountOut(priceInCumulativeStart, price0Cumulative, timeElapsed, amountIn); } //btch realtime price in wbtc function getBTCHBTC() public view returns(uint256){ if(btch==address(0)||wbtc==address(0)) { return 0; } (uint256 btchReserve/*reserveA*/,uint256 wbtcReserve/*reserveB*/)= UniswapV2Library.getReserves(susiFactory, btch/*tokenA*/, wbtc/*tokenB*/); if(btchReserve==0) { return 0; } return UniswapV2Library.quote(btchDecimal,btchReserve,wbtcReserve); } //btch avg price(24 hours) in wbtc function getBTCHBTC24() public view returns(uint256){ if(btch==address(0)) { return 0; } uint256 idx = block.timestamp/periodSize; uint256 i = idx - daySeconds/periodSize; uint startTime = pairObservations[btch][i].timestamp; uint priceStart = pairObservations[btch][i].price0Cumulative; if(priceStart==0) { for(;i<idx;i++) { priceStart = pairObservations[btch][i].price0Cumulative; if(priceStart>0) { startTime = pairObservations[btch][i].timestamp; break; } } } uint priceEnd = pairObservations[btch][idx].price0Cumulative; uint j=idx; uint endTime = pairObservations[btch][j].timestamp; if(priceEnd==0) { for(;j>i;j--) { priceEnd = pairObservations[btch][j].price0Cumulative; if(priceEnd>0) { endTime = pairObservations[btch][j].timestamp; break; } } } uint timeAvgPrice = getTimeAvgPrice(susiFactory,btch,btchDecimal,priceStart,priceEnd,startTime,endTime,wbtc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCHBTC(); } //btch realtime price in wbtc function getBTCUSDC() public view returns(uint256){ if(wbtc==address(0)||usdc==address(0)) { return 0; } (uint256 btcReserve/*reserveA*/,uint256 usdcReserve/*reserveB*/)= UniswapV2Library.getReserves(uniFactory, wbtc/*tokenA*/, usdc/*tokenB*/); if(btcReserve==0) { return 0; } return UniswapV2Library.quote(btcDecimal,btcReserve,usdcReserve); } //btc avg price(24 hours) in wbtc function getBTCUSDC24() public view returns(uint256){ if(wbtc==address(0)) { return 0; } uint256 idx = block.timestamp/periodSize; uint256 i = idx - daySeconds/periodSize; uint priceStart = pairObservations[wbtc][i].price0Cumulative; uint startTime = pairObservations[wbtc][i].timestamp; if(priceStart==0) { for(;i<idx;i++) { priceStart = pairObservations[wbtc][i].price0Cumulative; if(priceStart>0) { startTime = pairObservations[wbtc][i].timestamp; break; } } } uint priceEnd = pairObservations[wbtc][idx].price0Cumulative; uint j=idx; uint endTime = pairObservations[wbtc][j].timestamp; if(priceEnd==0) { for(;j>i;j--) { priceEnd = pairObservations[wbtc][j].price0Cumulative; if(priceEnd>0) { endTime = pairObservations[wbtc][j].timestamp; break; } } } uint timeAvgPrice = getTimeAvgPrice(uniFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCUSDC(); } function getBTCUSDC365() external view returns(uint256) { uint256 dayidx = block.timestamp/daySeconds; uint256 startIdx = dayidx -365; uint startTime = startIdx*daySeconds; uint priceStart = uiniAvgBtcDayCumulativePrice[startIdx]; if(priceStart==0) { for(;startIdx<dayidx;startIdx++) { priceStart = uiniAvgBtcDayCumulativePrice[startIdx]; if(priceStart>0) { startTime = startIdx*daySeconds; break; } } } uint priceEnd = uiniAvgBtcDayCumulativePrice[dayidx]; uint j=dayidx; uint endTime = j*daySeconds; if(priceEnd==0) { for(;j>startIdx;j--) { priceEnd = uiniAvgBtcDayCumulativePrice[j]; if(priceEnd>0) { endTime = j*daySeconds; break; } } } uint timeAvgPrice = getTimeAvgPrice(uniFactory,wbtc,btcDecimal,priceStart,priceEnd,startTime,endTime,usdc); if(timeAvgPrice>0) { return timeAvgPrice; } return getBTCUSDC24(); } function needUpdate() public view returns (bool) { uint256 idx = block.timestamp/periodSize; bool timeupdate = (block.timestamp-lastUpdateTime)>(periodSize/2); bool uniupdate = (pairObservations[wbtc][idx].timestamp==0); bool susiupdate = (pairObservations[btch][idx].timestamp==0); return (uniupdate&&susiupdate&&timeupdate); } function update() external { //will return if is not over periodSize/2 if((block.timestamp-lastUpdateTime)<(periodSize/2)) { return; } //update observation for uni btc day price updateOberverVation(); lastUpdateTime = block.timestamp; } // update the cumulative price for the observation at the current timestamp. each observation is updated at most // once per epoch period. function updateOberverVation() private { uint256 idx = block.timestamp/periodSize; uint256 price = 0; if(wbtc!=address(0)) { if(pairObservations[wbtc][idx].timestamp==0) { address pair = UniswapV2Library.pairFor(uniFactory,wbtc,usdc); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); price = getBTCUSDC(); pairObservations[wbtc][idx] = Observation(block.timestamp,price,price0Cumulative); //record day price0Cumulative uint256 dayidx = block.timestamp/daySeconds; if(uiniAvgBtcDayCumulativePrice[dayidx]==0) { uiniAvgBtcDayCumulativePrice[dayidx]=price0Cumulative; } emit SetBtcAvg24Price(msg.sender,price,idx); } } if(btch!=address(0)) { if(pairObservations[btch][idx].timestamp==0) { address pair = UniswapV2Library.pairFor(susiFactory,btch,wbtc); (uint price0Cumulative,,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); price = getBTCHBTC(); pairObservations[btch][idx] = Observation(block.timestamp,price,price0Cumulative); emit BtchAvg24Price(msg.sender,price,idx); } } } }
57,486
42
// Returns block.timestamp, overridable for test purposes.
function _now() internal view virtual returns (uint256) { return block.timestamp; }
function _now() internal view virtual returns (uint256) { return block.timestamp; }
27,967
40
// if no fee receiver is set send it to the baker
if(feeReceiver == address(0)) { feeReceiver_ = _msgSender(); }
if(feeReceiver == address(0)) { feeReceiver_ = _msgSender(); }
81,501
21
// had voted nothing to do more
if(p.voteState[trustee] == true) { return false; }
if(p.voteState[trustee] == true) { return false; }
7,614
6
// bytes
function setBytesAuto(bytes memory x) public { storedBytesAuto = x; }
function setBytesAuto(bytes memory x) public { storedBytesAuto = x; }
9,144
1
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
bytes memory buf = new bytes(64);
28,910
58
// Determine and set an account's balance based on a change in wei /
function setParFromDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Wei memory deltaWei ) internal
function setParFromDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Wei memory deltaWei ) internal
20,494
75
// Decode an RLPItem into an int. This will not work if the RLPItem is a list. self The RLPItem.return The decoded string./
function toInt(RLPItem memory self) internal pure returns (int data) { return int(toUint(self)); }
function toInt(RLPItem memory self) internal pure returns (int data) { return int(toUint(self)); }
28,525
5
// The balance of account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
function balanceOf(address _owner) public constant returns (uint256 balance);
25,700
149
// Supplies
uint256 public maxSupply = 777; uint256 public maxSupplyLimit = 777;
uint256 public maxSupply = 777; uint256 public maxSupplyLimit = 777;
48,752
154
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
mapping(address => mapping(address => bool)) public rewardDistributors;
4,865
91
// Get total fee's or multiplication of fees
function getTotalFee(bool selling) public view returns (uint256) { if(launchedAt + deadBlocks >= block.number){ return feeDenominator.sub(1); } if(selling && buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp){ return getMultipliedFee(); } return totalFee; }
function getTotalFee(bool selling) public view returns (uint256) { if(launchedAt + deadBlocks >= block.number){ return feeDenominator.sub(1); } if(selling && buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp){ return getMultipliedFee(); } return totalFee; }
29,934
198
// Admin Mint Functions/ Mints a token to an address with a tokenURI.This is owner only and allows a fee-free drop _to address of the future owner of the token _qty amount of tokens to drop the owner /
function mintToAdminV2(address _to, uint256 _qty) public onlyTeamOrOwner{ require(_qty > 0, "Must mint at least 1 token."); require(currentTokenId() + _qty <= collectionSize, "Cannot mint over supply cap of 88888"); _safeMint(_to, _qty, true); }
function mintToAdminV2(address _to, uint256 _qty) public onlyTeamOrOwner{ require(_qty > 0, "Must mint at least 1 token."); require(currentTokenId() + _qty <= collectionSize, "Cannot mint over supply cap of 88888"); _safeMint(_to, _qty, true); }
39,317
56
// Swaps one index for another in an array. /
function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; }
function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; }
27,077
377
// PRECISIONcfg.maxPlayerScore_etherContributed ) Compute timeFactors.
int referreeScore_timeFactors = ( ( ( hdata.referree_timeFactors - minMax.holderScore_timeFactors_min * refCount )
int referreeScore_timeFactors = ( ( ( hdata.referree_timeFactors - minMax.holderScore_timeFactors_min * refCount )
4,661
7
// Check if account is critical now (current host.getNow())A critical account is when availableBalance < 0account The account to check return isCritical Whether the account is critical/
function isAccountCriticalNow(
function isAccountCriticalNow(
5,027
1
// Capped Implementation of the Capped /
contract Capped is BEP20, ServicePayer, GeneratorCopyright("v2.0.0") { constructor ( string memory name, string memory symbol, address payable feeReceiver ) BEP20(name, symbol) ServicePayer(feeReceiver, "Capped") payable { _mint(_msgSender(), 100000e18); } }
contract Capped is BEP20, ServicePayer, GeneratorCopyright("v2.0.0") { constructor ( string memory name, string memory symbol, address payable feeReceiver ) BEP20(name, symbol) ServicePayer(feeReceiver, "Capped") payable { _mint(_msgSender(), 100000e18); } }
52,062
367
// Collateral price module
ICollybus collybus;
ICollybus collybus;
26,614
95
// registe a pool /
function addPool(address poolAddr) onlyGovernance public
function addPool(address poolAddr) onlyGovernance public
36,979
91
// Internal function to calculate the amount of strike asset needed given the option amount amountOfOptions Intended amount to options to mint /
function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) { uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals())); require(strikeAmount > 0, "PodOption: amount of options is too low"); return strikeAmount; }
function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) { uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals())); require(strikeAmount > 0, "PodOption: amount of options is too low"); return strikeAmount; }
36,067
26
// The created period can be edited by the admin. _poolIndex the index of the pool to be edited. _startTime pool start time in seconds. _duration pool duration time in seconds. _apy the new apy ratio. _mainPenaltyRate the new main penalty rate. _subPenaltyRate the new sub penalty rate. _lockedLimit maximum amount of tokens that can be locked for this pool Reverts if the pool is not empty. Reverts if the pool is not created before. /
function editPool( uint256 _poolIndex, uint256 _startTime, uint256 _duration, uint256 _apy, uint256 _mainPenaltyRate, uint256 _subPenaltyRate, uint256 _lockedLimit, bool _nftReward )
function editPool( uint256 _poolIndex, uint256 _startTime, uint256 _duration, uint256 _apy, uint256 _mainPenaltyRate, uint256 _subPenaltyRate, uint256 _lockedLimit, bool _nftReward )
1,951
17
// ============ Constructor ============ //Initializes the controller_controllerInstance of the controller /
constructor(IController _controller) public { controller = _controller; }
constructor(IController _controller) public { controller = _controller; }
9,038
64
// Public functions //Constructor sets events contract address
function PlayToken() public { creator = msg.sender; }
function PlayToken() public { creator = msg.sender; }
45,744
93
// require(amountInWei <= 1 ether, "May not buy more than 1 ETH in a single buy to reduce sandwich attacks");
address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this);
address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this);
18,050
83
// var averageCostPerToken = div(numTokens , numEther);averageBuyInPrice[sender] = div( totalSpentBefore + mul( averageCostPerToken , numTokens), newTokenSum );
46,384
161
// Private Functions // Creates a hash from a message struct._message The message to hash. return messageHash_ The hash that represents this message. /
function messageDigest( Message storage _message ) private view returns (bytes32 messageHash_)
function messageDigest( Message storage _message ) private view returns (bytes32 messageHash_)
25,159
0
// ERC721 basic token contract being held
IERC721 immutable private _token;
IERC721 immutable private _token;
7,964
18
// Integer division of two signed integers truncating the quotient, reverts on division by zero. /
function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "wdivision by zero"); require(!(b == -1 && a == _INT256_MIN), "wdivision overflow"); int256 c = a / b; return c; }
function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "wdivision by zero"); require(!(b == -1 && a == _INT256_MIN), "wdivision overflow"); int256 c = a / b; return c; }
7,445
19
// Changes the controller of the contract/_newController The new controller of the contract
function setController(address _newController) public onlyOwner { controller = _newController; }
function setController(address _newController) public onlyOwner { controller = _newController; }
16,221
681
// Check balance
uint256 balance = IERC20(sdvd).balanceOf(address(this));
uint256 balance = IERC20(sdvd).balanceOf(address(this));
74,205
4
// a custom revert error of handleOps, to identify the offending op. NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)reason - revert reason The string starts with a unique code "AAmn", where "m" is "1" for factory, "2" for account and "3" for paymaster issues, so a failure can be attributed to the correct entity.Should be caught in off-chain handleOps simulation and not happen on-chain.Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster
error FailedOp(uint256 opIndex, string reason);
error FailedOp(uint256 opIndex, string reason);
30,732
4
// BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as there is no wrapped balance).
return _toNominal(mainIn, params);
return _toNominal(mainIn, params);
20,906
19
// Returns all sold bid items/
function getSoldNFTs() public view returns (Auctions[] memory) { uint soldItemCount = _soldCounter.current(); uint currentIndex = 0; Auctions[] memory items = new Auctions[](soldItemCount); for (uint i = 0; i < soldItemCount; i++) { uint currentId = i + 1; Auctions storage currentItem = auction[currentId]; if (currentItem.auctionState == State.Ended) { items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
function getSoldNFTs() public view returns (Auctions[] memory) { uint soldItemCount = _soldCounter.current(); uint currentIndex = 0; Auctions[] memory items = new Auctions[](soldItemCount); for (uint i = 0; i < soldItemCount; i++) { uint currentId = i + 1; Auctions storage currentItem = auction[currentId]; if (currentItem.auctionState == State.Ended) { items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
25,589
5
// payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); transfer doesn't work as expected when receiving contract is proxified so using call
(bool success, /* bytes memory data */) = ethPredicateAddress.call{value: msg.value}("");
(bool success, /* bytes memory data */) = ethPredicateAddress.call{value: msg.value}("");
17,675