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
85
// Whitelists an address to allow calling BetaDelegatedTransfer. _addr The new address to whitelist. /
function whitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(!betaDelegateWhitelist[_addr], "delegate already whitelisted"); betaDelegateWhitelist[_addr] = true; emit BetaDelegateWhitelisted(_addr); }
function whitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(!betaDelegateWhitelist[_addr], "delegate already whitelisted"); betaDelegateWhitelist[_addr] = true; emit BetaDelegateWhitelisted(_addr); }
28,020
106
// IERC1363Receiver Interface Interface for any contract that wants to support transferAndCall or transferFromAndCall from ERC1363 token contracts as defined in /
interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4); }
interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4); }
3,877
7
// Lock the Carve in the contract
carve.transferFrom(msg.sender, address(this), amount);
carve.transferFrom(msg.sender, address(this), amount);
34,284
17
// softPullReward calculates the reward accumulated since the last time it was called but does not actually execute the transfers. Instead, it adds the amount to rewardNotTransferred variable
function softPullReward(address token) internal { uint256 lastPullTs = lastSoftPullTs[token]; // no need to execute multiple times in the same block if (lastPullTs == block.timestamp) { return; } uint256 rate = rewardRatesPerSecond[token]; address source = rewardSources[token]; // don't execute if the setup was not completed if (rate == 0 || source == address(0)) { return; } // if there's no allowance left on the source contract, don't try to pull anything else uint256 allowance = IERC20(token).allowance(source, address(this)); uint256 rewardNotTransferred = rewardsNotTransferred[token]; if (allowance == 0 || allowance <= rewardNotTransferred) { lastSoftPullTs[token] = block.timestamp; return; } uint256 timeSinceLastPull = block.timestamp.sub(lastPullTs); uint256 amountToPull = timeSinceLastPull.mul(rate); // only pull the minimum between allowance left and the amount that should be pulled for the period uint256 allowanceLeft = allowance.sub(rewardNotTransferred); if (amountToPull > allowanceLeft) { amountToPull = allowanceLeft; } rewardsNotTransferred[token] = rewardNotTransferred.add(amountToPull); lastSoftPullTs[token] = block.timestamp; }
function softPullReward(address token) internal { uint256 lastPullTs = lastSoftPullTs[token]; // no need to execute multiple times in the same block if (lastPullTs == block.timestamp) { return; } uint256 rate = rewardRatesPerSecond[token]; address source = rewardSources[token]; // don't execute if the setup was not completed if (rate == 0 || source == address(0)) { return; } // if there's no allowance left on the source contract, don't try to pull anything else uint256 allowance = IERC20(token).allowance(source, address(this)); uint256 rewardNotTransferred = rewardsNotTransferred[token]; if (allowance == 0 || allowance <= rewardNotTransferred) { lastSoftPullTs[token] = block.timestamp; return; } uint256 timeSinceLastPull = block.timestamp.sub(lastPullTs); uint256 amountToPull = timeSinceLastPull.mul(rate); // only pull the minimum between allowance left and the amount that should be pulled for the period uint256 allowanceLeft = allowance.sub(rewardNotTransferred); if (amountToPull > allowanceLeft) { amountToPull = allowanceLeft; } rewardsNotTransferred[token] = rewardNotTransferred.add(amountToPull); lastSoftPullTs[token] = block.timestamp; }
1,985
109
// This contract represents a bunch of bills of exchange issued by one person at the same time and on the same conditions /
contract BillsOfExchange is BurnableToken { /* ---- Bill of Exchange requisites: */ /** * Number of this contract in the ledger maintained by factory contract */ uint256 public billsOfExchangeContractNumber; /** * Legal name of a person who issues the bill (drawer) * This can be a name of a company/organization or of a physical person */ string public drawerName; /** * Ethereum address of the signer * His/her identity has to be verified via Cryptonomica.net smart contract */ address public drawerRepresentedBy; /** * Link to information about signer's authority to represent the drawer * This should be a proof that signer can represent drawer * It can be link to public register like Companies House in U.K., or other proof. * Whosoever puts his signature on a bill of exchange as representing a person for whom he had no power to act is * bound himself as a party to the bill. The same rule applies to a representative who has exceeded his powers. */ string public linkToSignersAuthorityToRepresentTheDrawer; /** * The name of the person who is to pay (drawee) */ string public drawee; /** * Ethereum address of a person who can represent the drawee * This address should be verified via Cryptonomica.net smart contract */ address public draweeSignerAddress; /** * This should be a proof that signer can represent drawee. */ string public linkToSignersAuthorityToRepresentTheDrawee; /* * Legal conditions to be included */ string public description; string public order; string public disputeResolutionAgreement; CryptonomicaVerification public cryptonomicaVerification; /* * a statement of the time of payment * we use string to make possible variants like: '01 Jan 2021', 'at sight', 'at sight but not before 2019-12-31' * '10 days after sight' etc., * see https://www.jus.uio.no/lm/bills.of.exchange.and.promissory.notes.convention.1930/doc.html#109 */ string public timeOfPayment; // A statement of the date and of the place where the bill is issued uint256 public issuedOnUnixTime; string public placeWhereTheBillIsIssued; // i.e. "London, U.K."; // a statement of the place where payment is to be made; // usually it is an address of the payer string public placeWherePaymentIsToBeMade; // https://en.wikipedia.org/wiki/ISO_4217 // or crypto currency string public currency; // for example: "EUR", "USD" uint256 public sumToBePaidForEveryToken; // /* * number of signatures under disputeResolution agreement */ uint256 public disputeResolutionAgreementSignaturesCounter; /* * @param signatoryAddress Ethereum address of the person, that signed the agreement * @param signatoryName Legal name of the person that signed agreement. This can be a name of a legal or physical * person */ struct Signature { address signatoryAddress; string signatoryName; } mapping(uint256 => Signature) public disputeResolutionAgreementSignatures; /* * Event to be emitted when disputeResolution agreement was signed by new person * @param signatureNumber Number of the signature (see 'disputeResolutionAgreementSignaturesCounter') * @param singedBy Name of the person who signed disputeResolution agreement * @param representedBy Ethereum address of the person who signed disputeResolution agreement * @param signedOn Timestamp (Unix time) */ event disputeResolutionAgreementSigned( uint256 indexed signatureNumber, string signedBy, address indexed representedBy, uint256 signedOn ); /* * @param _signatoryAddress Ethereum address of the person who signs agreement * @param _signatoryName Name of the person that signs dispute resolution agreement */ function signDisputeResolutionAgreementFor( address _signatoryAddress, string memory _signatoryName ) public returns (bool success){ require( msg.sender == _signatoryAddress || msg.sender == creator, "Not authorized to sign dispute resolution agreement" ); // ! signer should have valid identity verification in cryptonomica.net smart contract: require( cryptonomicaVerification.keyCertificateValidUntil(_signatoryAddress) > now, "Signer has to be verified on Cryptonomica.net" ); // revokedOn returns uint256 (unix time), it's 0 if verification is not revoked require( cryptonomicaVerification.revokedOn(_signatoryAddress) == 0, "Verification for this address was revoked, can not sign" ); disputeResolutionAgreementSignaturesCounter++; disputeResolutionAgreementSignatures[disputeResolutionAgreementSignaturesCounter].signatoryAddress = _signatoryAddress; disputeResolutionAgreementSignatures[disputeResolutionAgreementSignaturesCounter].signatoryName = _signatoryName; emit disputeResolutionAgreementSigned(disputeResolutionAgreementSignaturesCounter, _signatoryName, msg.sender, now); return true; } function signDisputeResolutionAgreement(string calldata _signatoryName) external returns (bool success){ return signDisputeResolutionAgreementFor(msg.sender, _signatoryName); } /** * set up new bunch of bills of exchange and sign dispute resolution agreement * * @param _billsOfExchangeContractNumber A number of this contract in the ledger ('billsOfExchangeContractsCounter' from BillsOfExchangeFactory) * @param _currency Currency of the payment, for example: "EUR", "USD" * @param _sumToBePaidForEveryToken The amount in the above currency, that have to be paid for every token (bill of exchange) * @param _drawerName The person who issues the bill (drawer) * @param _drawerRepresentedBy The Ethereum address of the signer * @param _linkToSignersAuthorityToRepresentTheDrawer Link to information about signers authority to represent the drawer * @param _drawee The name of the person who is to pay (can be the same as drawer) */ function initBillsOfExchange( uint256 _billsOfExchangeContractNumber, string calldata _currency, uint256 _sumToBePaidForEveryToken, string calldata _drawerName, address _drawerRepresentedBy, string calldata _linkToSignersAuthorityToRepresentTheDrawer, string calldata _drawee, address _draweeSignerAddress ) external { require(msg.sender == creator, "Only contract creator can call 'initBillsOfExchange' function"); billsOfExchangeContractNumber = _billsOfExchangeContractNumber; // https://en.wikipedia.org/wiki/ISO_4217 // or crypto currency currency = _currency; sumToBePaidForEveryToken = _sumToBePaidForEveryToken; // person who issues the bill (drawer) drawerName = _drawerName; drawerRepresentedBy = _drawerRepresentedBy; linkToSignersAuthorityToRepresentTheDrawer = _linkToSignersAuthorityToRepresentTheDrawer; // order to // (the name of the person who is to pay) drawee = _drawee; draweeSignerAddress = _draweeSignerAddress; } /** * Set places and time * not included in 'init' because of exception: 'Stack too deep, try using fewer variables.' * @param _timeOfPayment The time when payment has to be made * @param _placeWhereTheBillIsIssued Place where the bills were issued. Usually it's the address of the drawer. * @param _placeWherePaymentIsToBeMade Place where the payment has to be made. Usually it's the address of the drawee. */ function setPlacesAndTime( string calldata _timeOfPayment, string calldata _placeWhereTheBillIsIssued, string calldata _placeWherePaymentIsToBeMade ) external { require(msg.sender == creator, "Only contract creator can call 'setPlacesAndTime' function"); // require(issuedOnUnixTime == 0, "setPlacesAndTime can be called one time only"); // (this can be ensured in factory contract) issuedOnUnixTime = now; timeOfPayment = _timeOfPayment; placeWhereTheBillIsIssued = _placeWhereTheBillIsIssued; placeWherePaymentIsToBeMade = _placeWherePaymentIsToBeMade; } /* * @param _description Legal description of bills of exchange created. * @param _order Order to pay (text or the order) * @param _disputeResolutionAgreement Agreement about dispute resolution (text) * this function should be called only once - when initializing smart contract */ function setLegal( string calldata _description, string calldata _order, string calldata _disputeResolutionAgreement, address _cryptonomicaVerificationAddress ) external { require(msg.sender == creator, "Only contract creator can call 'setLegal' function"); // require(address(cryptonomicaVerification) == address(0), "setLegal can be called one time only"); // (this can be ensured in factory contract) description = _description; order = _order; disputeResolutionAgreement = _disputeResolutionAgreement; cryptonomicaVerification = CryptonomicaVerification(_cryptonomicaVerificationAddress); } uint256 public acceptedOnUnixTime; /** * Drawee can accept only all bills in the smart contract, or not accept at all * @param acceptedOnUnixTime Time when drawee accepted bills * @param drawee The name of the drawee * @param draweeRepresentedBy The Ethereum address of the drawee's representative * (or drawee himself if he is a physical person) */ event Acceptance( uint256 acceptedOnUnixTime, string drawee, address draweeRepresentedBy ); /** * function for drawee to accept bill of exchange * see: * http://www.legislation.gov.uk/ukpga/Vict/45-46/61/section/17 * https://www.jus.uio.no/lm/bills.of.exchange.and.promissory.notes.convention.1930/doc.html#69 * * @param _linkToSignersAuthorityToRepresentTheDrawee Link to information about signer's authority to represent the drawee */ function accept(string calldata _linkToSignersAuthorityToRepresentTheDrawee) external returns (bool success) { /* * this should be called only by address, previously indicated as drawee's address by the drawer * or by BillsOfExchangeFactory address via 'createAndAcceptBillsOfExchange' function */ require( msg.sender == draweeSignerAddress || msg.sender == creator, "Not authorized to accept" ); signDisputeResolutionAgreementFor(draweeSignerAddress, drawee); linkToSignersAuthorityToRepresentTheDrawee = _linkToSignersAuthorityToRepresentTheDrawee; acceptedOnUnixTime = now; emit Acceptance(acceptedOnUnixTime, drawee, msg.sender); return true; } }
contract BillsOfExchange is BurnableToken { /* ---- Bill of Exchange requisites: */ /** * Number of this contract in the ledger maintained by factory contract */ uint256 public billsOfExchangeContractNumber; /** * Legal name of a person who issues the bill (drawer) * This can be a name of a company/organization or of a physical person */ string public drawerName; /** * Ethereum address of the signer * His/her identity has to be verified via Cryptonomica.net smart contract */ address public drawerRepresentedBy; /** * Link to information about signer's authority to represent the drawer * This should be a proof that signer can represent drawer * It can be link to public register like Companies House in U.K., or other proof. * Whosoever puts his signature on a bill of exchange as representing a person for whom he had no power to act is * bound himself as a party to the bill. The same rule applies to a representative who has exceeded his powers. */ string public linkToSignersAuthorityToRepresentTheDrawer; /** * The name of the person who is to pay (drawee) */ string public drawee; /** * Ethereum address of a person who can represent the drawee * This address should be verified via Cryptonomica.net smart contract */ address public draweeSignerAddress; /** * This should be a proof that signer can represent drawee. */ string public linkToSignersAuthorityToRepresentTheDrawee; /* * Legal conditions to be included */ string public description; string public order; string public disputeResolutionAgreement; CryptonomicaVerification public cryptonomicaVerification; /* * a statement of the time of payment * we use string to make possible variants like: '01 Jan 2021', 'at sight', 'at sight but not before 2019-12-31' * '10 days after sight' etc., * see https://www.jus.uio.no/lm/bills.of.exchange.and.promissory.notes.convention.1930/doc.html#109 */ string public timeOfPayment; // A statement of the date and of the place where the bill is issued uint256 public issuedOnUnixTime; string public placeWhereTheBillIsIssued; // i.e. "London, U.K."; // a statement of the place where payment is to be made; // usually it is an address of the payer string public placeWherePaymentIsToBeMade; // https://en.wikipedia.org/wiki/ISO_4217 // or crypto currency string public currency; // for example: "EUR", "USD" uint256 public sumToBePaidForEveryToken; // /* * number of signatures under disputeResolution agreement */ uint256 public disputeResolutionAgreementSignaturesCounter; /* * @param signatoryAddress Ethereum address of the person, that signed the agreement * @param signatoryName Legal name of the person that signed agreement. This can be a name of a legal or physical * person */ struct Signature { address signatoryAddress; string signatoryName; } mapping(uint256 => Signature) public disputeResolutionAgreementSignatures; /* * Event to be emitted when disputeResolution agreement was signed by new person * @param signatureNumber Number of the signature (see 'disputeResolutionAgreementSignaturesCounter') * @param singedBy Name of the person who signed disputeResolution agreement * @param representedBy Ethereum address of the person who signed disputeResolution agreement * @param signedOn Timestamp (Unix time) */ event disputeResolutionAgreementSigned( uint256 indexed signatureNumber, string signedBy, address indexed representedBy, uint256 signedOn ); /* * @param _signatoryAddress Ethereum address of the person who signs agreement * @param _signatoryName Name of the person that signs dispute resolution agreement */ function signDisputeResolutionAgreementFor( address _signatoryAddress, string memory _signatoryName ) public returns (bool success){ require( msg.sender == _signatoryAddress || msg.sender == creator, "Not authorized to sign dispute resolution agreement" ); // ! signer should have valid identity verification in cryptonomica.net smart contract: require( cryptonomicaVerification.keyCertificateValidUntil(_signatoryAddress) > now, "Signer has to be verified on Cryptonomica.net" ); // revokedOn returns uint256 (unix time), it's 0 if verification is not revoked require( cryptonomicaVerification.revokedOn(_signatoryAddress) == 0, "Verification for this address was revoked, can not sign" ); disputeResolutionAgreementSignaturesCounter++; disputeResolutionAgreementSignatures[disputeResolutionAgreementSignaturesCounter].signatoryAddress = _signatoryAddress; disputeResolutionAgreementSignatures[disputeResolutionAgreementSignaturesCounter].signatoryName = _signatoryName; emit disputeResolutionAgreementSigned(disputeResolutionAgreementSignaturesCounter, _signatoryName, msg.sender, now); return true; } function signDisputeResolutionAgreement(string calldata _signatoryName) external returns (bool success){ return signDisputeResolutionAgreementFor(msg.sender, _signatoryName); } /** * set up new bunch of bills of exchange and sign dispute resolution agreement * * @param _billsOfExchangeContractNumber A number of this contract in the ledger ('billsOfExchangeContractsCounter' from BillsOfExchangeFactory) * @param _currency Currency of the payment, for example: "EUR", "USD" * @param _sumToBePaidForEveryToken The amount in the above currency, that have to be paid for every token (bill of exchange) * @param _drawerName The person who issues the bill (drawer) * @param _drawerRepresentedBy The Ethereum address of the signer * @param _linkToSignersAuthorityToRepresentTheDrawer Link to information about signers authority to represent the drawer * @param _drawee The name of the person who is to pay (can be the same as drawer) */ function initBillsOfExchange( uint256 _billsOfExchangeContractNumber, string calldata _currency, uint256 _sumToBePaidForEveryToken, string calldata _drawerName, address _drawerRepresentedBy, string calldata _linkToSignersAuthorityToRepresentTheDrawer, string calldata _drawee, address _draweeSignerAddress ) external { require(msg.sender == creator, "Only contract creator can call 'initBillsOfExchange' function"); billsOfExchangeContractNumber = _billsOfExchangeContractNumber; // https://en.wikipedia.org/wiki/ISO_4217 // or crypto currency currency = _currency; sumToBePaidForEveryToken = _sumToBePaidForEveryToken; // person who issues the bill (drawer) drawerName = _drawerName; drawerRepresentedBy = _drawerRepresentedBy; linkToSignersAuthorityToRepresentTheDrawer = _linkToSignersAuthorityToRepresentTheDrawer; // order to // (the name of the person who is to pay) drawee = _drawee; draweeSignerAddress = _draweeSignerAddress; } /** * Set places and time * not included in 'init' because of exception: 'Stack too deep, try using fewer variables.' * @param _timeOfPayment The time when payment has to be made * @param _placeWhereTheBillIsIssued Place where the bills were issued. Usually it's the address of the drawer. * @param _placeWherePaymentIsToBeMade Place where the payment has to be made. Usually it's the address of the drawee. */ function setPlacesAndTime( string calldata _timeOfPayment, string calldata _placeWhereTheBillIsIssued, string calldata _placeWherePaymentIsToBeMade ) external { require(msg.sender == creator, "Only contract creator can call 'setPlacesAndTime' function"); // require(issuedOnUnixTime == 0, "setPlacesAndTime can be called one time only"); // (this can be ensured in factory contract) issuedOnUnixTime = now; timeOfPayment = _timeOfPayment; placeWhereTheBillIsIssued = _placeWhereTheBillIsIssued; placeWherePaymentIsToBeMade = _placeWherePaymentIsToBeMade; } /* * @param _description Legal description of bills of exchange created. * @param _order Order to pay (text or the order) * @param _disputeResolutionAgreement Agreement about dispute resolution (text) * this function should be called only once - when initializing smart contract */ function setLegal( string calldata _description, string calldata _order, string calldata _disputeResolutionAgreement, address _cryptonomicaVerificationAddress ) external { require(msg.sender == creator, "Only contract creator can call 'setLegal' function"); // require(address(cryptonomicaVerification) == address(0), "setLegal can be called one time only"); // (this can be ensured in factory contract) description = _description; order = _order; disputeResolutionAgreement = _disputeResolutionAgreement; cryptonomicaVerification = CryptonomicaVerification(_cryptonomicaVerificationAddress); } uint256 public acceptedOnUnixTime; /** * Drawee can accept only all bills in the smart contract, or not accept at all * @param acceptedOnUnixTime Time when drawee accepted bills * @param drawee The name of the drawee * @param draweeRepresentedBy The Ethereum address of the drawee's representative * (or drawee himself if he is a physical person) */ event Acceptance( uint256 acceptedOnUnixTime, string drawee, address draweeRepresentedBy ); /** * function for drawee to accept bill of exchange * see: * http://www.legislation.gov.uk/ukpga/Vict/45-46/61/section/17 * https://www.jus.uio.no/lm/bills.of.exchange.and.promissory.notes.convention.1930/doc.html#69 * * @param _linkToSignersAuthorityToRepresentTheDrawee Link to information about signer's authority to represent the drawee */ function accept(string calldata _linkToSignersAuthorityToRepresentTheDrawee) external returns (bool success) { /* * this should be called only by address, previously indicated as drawee's address by the drawer * or by BillsOfExchangeFactory address via 'createAndAcceptBillsOfExchange' function */ require( msg.sender == draweeSignerAddress || msg.sender == creator, "Not authorized to accept" ); signDisputeResolutionAgreementFor(draweeSignerAddress, drawee); linkToSignersAuthorityToRepresentTheDrawee = _linkToSignersAuthorityToRepresentTheDrawee; acceptedOnUnixTime = now; emit Acceptance(acceptedOnUnixTime, drawee, msg.sender); return true; } }
26,878
3
// 从消息发送者账户中往_to账户转数量为_value的token
function transfer(address _to, uint256 _value) returns (bool success);
function transfer(address _to, uint256 _value) returns (bool success);
46,808
11
// Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper( address to, uint256 value, address _nativeTokenWrapper
function safeTransferNativeTokenWithWrapper( address to, uint256 value, address _nativeTokenWrapper
2,840
33
// count confirmation
uint256 remaining;
uint256 remaining;
46,756
3
// Time duration for a Grace
uint256 public gracePeriod;
uint256 public gracePeriod;
20,739
6
// Liquidity Pool Converter The liquidity pool converter is the base contract for specific types of converters thatmanage liquidity pools. Liquidity pools have 2 reserves or more and they allow converting between them. Note that TokenRateUpdate events are dispatched for pool tokens as well.The pool token is the first token in the event in that case. /
contract LiquidityPoolConverter is ConverterBase { /** * @dev triggered after liquidity is added * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityAdded(address indexed _provider, address indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply); /** * @dev triggered after liquidity is removed * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityRemoved(address indexed _provider, address indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply); /** * @dev initializes a new LiquidityPoolConverter instance * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee ) internal ConverterBase(_anchor, _registry, _maxConversionFee) {} /** * @dev accepts ownership of the anchor after an ownership transfer * also activates the converter * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public { // verify that the converter has at least 2 reserves require(reserveTokenCount() > 1, "ERR_INVALID_RESERVE_COUNT"); super.acceptAnchorOwnership(); } }
contract LiquidityPoolConverter is ConverterBase { /** * @dev triggered after liquidity is added * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityAdded(address indexed _provider, address indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply); /** * @dev triggered after liquidity is removed * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityRemoved(address indexed _provider, address indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply); /** * @dev initializes a new LiquidityPoolConverter instance * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee ) internal ConverterBase(_anchor, _registry, _maxConversionFee) {} /** * @dev accepts ownership of the anchor after an ownership transfer * also activates the converter * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public { // verify that the converter has at least 2 reserves require(reserveTokenCount() > 1, "ERR_INVALID_RESERVE_COUNT"); super.acceptAnchorOwnership(); } }
46,167
140
// leave one gwei to lower future claim gas costs https:twitter.com/libevm/status/1474870670429360129?s=21
_balance -= 1;
_balance -= 1;
43,809
14
// Default methodProcesses all ETH that it receives and credits TKLN tokens to senderaccording to current stage bonus/
function () external payable { processPayment(msg.sender, msg.value); }
function () external payable { processPayment(msg.sender, msg.value); }
17,401
2
// 描述
string description;
string description;
36,932
178
// gets existing loan/loanId id of existing loan/ return loanData array of loans
function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData);
function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData);
3,832
27
// This function is for testing purpose for distributing the royalty payment/royaltyIdParam This is the id of royalty that user wants to claim/tokenId this is the id of token that determines the royalty amount
function _calculateSingleRoyaltyAmount( uint256 royaltyIdParam, uint256 tokenId
function _calculateSingleRoyaltyAmount( uint256 royaltyIdParam, uint256 tokenId
23,436
191
// previously they were not voting
else if (old == 0) { uint256 averageReserve = reserveTotal / votingTokens; uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; require(_new >= reservePriceMin, "update:reserve price too low"); uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; require(_new <= reservePriceMax, "update:reserve price too high"); votingTokens += weight; reserveTotal += weight * _new;
else if (old == 0) { uint256 averageReserve = reserveTotal / votingTokens; uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; require(_new >= reservePriceMin, "update:reserve price too low"); uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; require(_new <= reservePriceMax, "update:reserve price too high"); votingTokens += weight; reserveTotal += weight * _new;
32,644
23
// round 13
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
26,296
128
// zero qty
require(count != 0, "ZERO_QUANTITY");
require(count != 0, "ZERO_QUANTITY");
70,336
156
// Presence of this function indicates the contract is a Custom Token./
function isCustomToken() public pure returns(bool isCustom) { return true; }
function isCustomToken() public pure returns(bool isCustom) { return true; }
40,479
197
// Increment buffer length - 0xe0 plus the original length
mstore(ptr, add(0xe0, mload(ptr)))
mstore(ptr, add(0xe0, mload(ptr)))
60,745
10
// 删除一个申请案 /
function removeStockRightApply(string memory uniScId,string memory investorCetfHash) public onlyProxy returns (bool){ delete stockRightApplys[uniScId][investorCetfHash]; ArrayUtils.remove(stockRightApplyKeys[uniScId],investorCetfHash); return true; }
function removeStockRightApply(string memory uniScId,string memory investorCetfHash) public onlyProxy returns (bool){ delete stockRightApplys[uniScId][investorCetfHash]; ArrayUtils.remove(stockRightApplyKeys[uniScId],investorCetfHash); return true; }
16,119
18
// calculate remaining tokens and leave 25% for manual allocation
c_maximumTokensSold = m_token.balanceOf(this).sub( m_token.totalSupply().div(4) );
c_maximumTokensSold = m_token.balanceOf(this).sub( m_token.totalSupply().div(4) );
49,905
6
// TODO Create a function to add the solutions to the array and emit the event
function _addSolution(address _to, uint256 _tokenId, bytes32 _key) internal
function _addSolution(address _to, uint256 _tokenId, bytes32 _key) internal
10,423
79
// Internal function to create a new ACO pool. initData Data to initialize o ACO Pool.return Address of the new minimal proxy deployed for the ACO pool. /
function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { address acoPool = _deployAcoPool(initData); acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall); emit NewAcoPool( initData.underlying, initData.strikeAsset, initData.isCall, acoPool, acoPoolImplementation ); return acoPool; }
function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { address acoPool = _deployAcoPool(initData); acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall); emit NewAcoPool( initData.underlying, initData.strikeAsset, initData.isCall, acoPool, acoPoolImplementation ); return acoPool; }
35,719
48
// BatchNoConversionPaymentsThis contract makes multiple payments with references, in one transaction: - on: ERC20 Payment Proxy and ETH Payment Proxy of the Request Network protocol - to: multiple addresses - fees: ERC20 and ETH proxies fees are paid to the same address. An additional batch fee is paid to the same address.If one transaction of the batch fail, every transactions are reverted. It is a clone of BatchPayment.sol, with three main modifications:- function "receive" has one other condition: payerAuthorized- fees are now divided by 10_000 instead of 1_000 in previous version- batch payment functions have new names and are now public,
contract BatchNoConversionPayments is Ownable { using SafeERC20 for IERC20; IERC20FeeProxy public paymentErc20Proxy; IEthereumFeeProxy public paymentEthProxy; uint256 public batchFee; /** Used to to calculate batch fees */ uint256 internal tenThousand = 10000; // payerAuthorized is set to true only when needed for batch Eth conversion bool internal payerAuthorized; // transferBackRemainingEth is set to false only if the payer use batchRouter // and call both batchEthPayments and batchConversionEthPaymentsWithReference bool internal transferBackRemainingEth = true; struct Token { address tokenAddress; uint256 amountAndFee; uint256 batchFeeAmount; } /** * @param _paymentErc20Proxy The address to the ERC20 fee payment proxy to use. * @param _paymentEthProxy The address to the Ethereum fee payment proxy to use. * @param _owner Owner of the contract. */ constructor( address _paymentErc20Proxy, address _paymentEthProxy, address _owner ) { paymentErc20Proxy = IERC20FeeProxy(_paymentErc20Proxy); paymentEthProxy = IEthereumFeeProxy(_paymentEthProxy); transferOwnership(_owner); batchFee = 0; } /** * This contract is non-payable. Making an ETH payment with conversion requires the contract to accept incoming ETH. * @dev See the end of `paymentEthConversionProxy.transferWithReferenceAndFee` where the leftover is given back. */ receive() external payable { require(payerAuthorized || msg.value == 0, 'Non-payable'); } /** * @notice Send a batch of ETH (or EVM native token) payments with fees and paymentReferences to multiple accounts. * If one payment fails, the whole batch reverts. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List fee amounts, matching recipients[]. * @param _feeAddress The fee recipient. * @dev It uses EthereumFeeProxy to pay an invoice and fees with a payment reference. * Make sure: msg.value >= sum(_amouts)+sum(_feeAmounts)+sumBatchFeeAmount */ function batchEthPayments( address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address payable _feeAddress ) public payable { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and then used as batch fee amount uint256 amount = 0; // Batch contract pays the requests thourgh EthFeeProxy for (uint256 i = 0; i < _recipients.length; i++) { require(address(this).balance >= _amounts[i] + _feeAmounts[i], 'not enough funds'); amount += _amounts[i]; paymentEthProxy.transferWithReferenceAndFee{value: _amounts[i] + _feeAmounts[i]}( payable(_recipients[i]), _paymentReferences[i], _feeAmounts[i], payable(_feeAddress) ); } // amount is updated into batch fee amount amount = (amount * batchFee) / tenThousand; // Check that batch contract has enough funds to pay batch fee require(address(this).balance >= amount, 'not enough funds for batch fee'); // Batch pays batch fee _feeAddress.transfer(amount); // Batch contract transfers the remaining ethers to the payer if (transferBackRemainingEth && address(this).balance > 0) { (bool sendBackSuccess, ) = payable(msg.sender).call{value: address(this).balance}(''); require(sendBackSuccess, 'Could not send remaining funds to the payer'); } } /** * @notice Send a batch of ERC20 payments with fees and paymentReferences to multiple accounts. * @param _tokenAddress Token used for all the payments. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List of payment fee amounts, matching recipients[]. * @param _feeAddress The fee recipient. * @dev Uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure this contract has enough allowance to spend the payer's token. * Make sure the payer has enough tokens to pay the amount, the fee, and the batch fee. */ function batchERC20Payments( address _tokenAddress, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) public { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and fee, and then used as batch fee amount uint256 amount = 0; for (uint256 i = 0; i < _recipients.length; i++) { amount += _amounts[i] + _feeAmounts[i]; } // Transfer the amount and fee from the payer to the batch contract IERC20 requestedToken = IERC20(_tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= amount, 'Insufficient allowance for batch to pay' ); require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds'); require( safeTransferFrom(_tokenAddress, address(this), amount), 'payment transferFrom() failed' ); // Batch contract approve Erc20FeeProxy to spend the token if (requestedToken.allowance(address(this), address(paymentErc20Proxy)) < amount) { approvePaymentProxyToSpend(address(requestedToken), address(paymentErc20Proxy)); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { // amount is updated to become the sum of amounts, to calculate batch fee amount amount -= _feeAmounts[i]; paymentErc20Proxy.transferFromWithReferenceAndFee( _tokenAddress, _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } // amount is updated into batch fee amount amount = (amount * batchFee) / tenThousand; // Check if the payer has enough funds to pay batch fee require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds for the batch fee'); // Payer pays batch fee amount require( safeTransferFrom(_tokenAddress, _feeAddress, amount), 'batch fee transferFrom() failed' ); } /** * @notice Send a batch of ERC20 payments with fees and paymentReferences to multiple accounts, with multiple tokens. * @param _tokenAddresses List of tokens to transact with. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List of amounts of the payment fee, matching recipients[]. * @param _feeAddress The fee recipient. * @dev It uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure this contract has enough allowance to spend the payer's token. * Make sure the payer has enough tokens to pay the amount, the fee, and the batch fee. */ function batchMultiERC20Payments( address[] calldata _tokenAddresses, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) public { require( _tokenAddresses.length == _recipients.length && _tokenAddresses.length == _amounts.length && _tokenAddresses.length == _paymentReferences.length && _tokenAddresses.length == _feeAmounts.length, 'the input arrays must have the same length' ); // Create a list of unique tokens used and the amounts associated // Only considere tokens having: amounts + feeAmounts > 0 // batchFeeAmount is the amount's sum, and then, batch fee rate is applied Token[] memory uTokens = new Token[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; i++) { for (uint256 j = 0; j < _tokenAddresses.length; j++) { // If the token is already in the existing uTokens list if (uTokens[j].tokenAddress == _tokenAddresses[i]) { uTokens[j].amountAndFee += _amounts[i] + _feeAmounts[i]; uTokens[j].batchFeeAmount += _amounts[i]; break; } // If the token is not in the list (amountAndFee = 0), and amount + fee > 0 if (uTokens[j].amountAndFee == 0 && (_amounts[i] + _feeAmounts[i]) > 0) { uTokens[j].tokenAddress = _tokenAddresses[i]; uTokens[j].amountAndFee = _amounts[i] + _feeAmounts[i]; uTokens[j].batchFeeAmount = _amounts[i]; break; } } } // The payer transfers tokens to the batch contract and pays batch fee for (uint256 i = 0; i < uTokens.length && uTokens[i].amountAndFee > 0; i++) { uTokens[i].batchFeeAmount = (uTokens[i].batchFeeAmount * batchFee) / tenThousand; IERC20 requestedToken = IERC20(uTokens[i].tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= uTokens[i].amountAndFee + uTokens[i].batchFeeAmount, 'Insufficient allowance for batch to pay' ); // check if the payer can pay the amount, the fee, and the batchFee require( requestedToken.balanceOf(msg.sender) >= uTokens[i].amountAndFee + uTokens[i].batchFeeAmount, 'not enough funds' ); // Transfer only the amount and fee required for the token on the batch contract require( safeTransferFrom(uTokens[i].tokenAddress, address(this), uTokens[i].amountAndFee), 'payment transferFrom() failed' ); // Batch contract approves Erc20FeeProxy to spend the token if ( requestedToken.allowance(address(this), address(paymentErc20Proxy)) < uTokens[i].amountAndFee ) { approvePaymentProxyToSpend(address(requestedToken), address(paymentErc20Proxy)); } // Payer pays batch fee amount require( safeTransferFrom(uTokens[i].tokenAddress, _feeAddress, uTokens[i].batchFeeAmount), 'batch fee transferFrom() failed' ); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { paymentErc20Proxy.transferFromWithReferenceAndFee( _tokenAddresses[i], _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } } /* * Helper functions */ /** * @notice Authorizes the proxy to spend a new request currency (ERC20). * @param _erc20Address Address of an ERC20 used as the request currency. * @param _paymentErc20Proxy Address of the proxy. */ function approvePaymentProxyToSpend(address _erc20Address, address _paymentErc20Proxy) internal { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(_paymentErc20Proxy), max); } /** * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call. * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value. * @return result The return value of the ERC20 call, returning true for non-standard tokens */ function safeTransferFrom( address _tokenAddress, address _to, uint256 _amount ) internal returns (bool result) { /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(_tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = _tokenAddress.call( abi.encodeWithSignature('transferFrom(address,address,uint256)', msg.sender, _to, _amount) ); assembly { switch returndatasize() case 0 { // Not a standard erc20 result := 1 } case 32 { // Standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // Anything else, should revert for safety revert(0, 0) } } require(success, 'transferFrom() has been reverted'); /* solium-enable security/no-inline-assembly */ return result; } /* * Admin functions to edit the proxies address and fees */ /** * @notice fees added when using Erc20/Eth batch functions * @param _batchFee between 0 and 10000, i.e: batchFee = 50 represent 0.50% of fee */ function setBatchFee(uint256 _batchFee) external onlyOwner { batchFee = _batchFee; } /** * @param _paymentErc20Proxy The address to the Erc20 fee payment proxy to use. */ function setPaymentErc20Proxy(address _paymentErc20Proxy) external onlyOwner { paymentErc20Proxy = IERC20FeeProxy(_paymentErc20Proxy); } /** * @param _paymentEthProxy The address to the Ethereum fee payment proxy to use. */ function setPaymentEthProxy(address _paymentEthProxy) external onlyOwner { paymentEthProxy = IEthereumFeeProxy(_paymentEthProxy); } }
contract BatchNoConversionPayments is Ownable { using SafeERC20 for IERC20; IERC20FeeProxy public paymentErc20Proxy; IEthereumFeeProxy public paymentEthProxy; uint256 public batchFee; /** Used to to calculate batch fees */ uint256 internal tenThousand = 10000; // payerAuthorized is set to true only when needed for batch Eth conversion bool internal payerAuthorized; // transferBackRemainingEth is set to false only if the payer use batchRouter // and call both batchEthPayments and batchConversionEthPaymentsWithReference bool internal transferBackRemainingEth = true; struct Token { address tokenAddress; uint256 amountAndFee; uint256 batchFeeAmount; } /** * @param _paymentErc20Proxy The address to the ERC20 fee payment proxy to use. * @param _paymentEthProxy The address to the Ethereum fee payment proxy to use. * @param _owner Owner of the contract. */ constructor( address _paymentErc20Proxy, address _paymentEthProxy, address _owner ) { paymentErc20Proxy = IERC20FeeProxy(_paymentErc20Proxy); paymentEthProxy = IEthereumFeeProxy(_paymentEthProxy); transferOwnership(_owner); batchFee = 0; } /** * This contract is non-payable. Making an ETH payment with conversion requires the contract to accept incoming ETH. * @dev See the end of `paymentEthConversionProxy.transferWithReferenceAndFee` where the leftover is given back. */ receive() external payable { require(payerAuthorized || msg.value == 0, 'Non-payable'); } /** * @notice Send a batch of ETH (or EVM native token) payments with fees and paymentReferences to multiple accounts. * If one payment fails, the whole batch reverts. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List fee amounts, matching recipients[]. * @param _feeAddress The fee recipient. * @dev It uses EthereumFeeProxy to pay an invoice and fees with a payment reference. * Make sure: msg.value >= sum(_amouts)+sum(_feeAmounts)+sumBatchFeeAmount */ function batchEthPayments( address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address payable _feeAddress ) public payable { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and then used as batch fee amount uint256 amount = 0; // Batch contract pays the requests thourgh EthFeeProxy for (uint256 i = 0; i < _recipients.length; i++) { require(address(this).balance >= _amounts[i] + _feeAmounts[i], 'not enough funds'); amount += _amounts[i]; paymentEthProxy.transferWithReferenceAndFee{value: _amounts[i] + _feeAmounts[i]}( payable(_recipients[i]), _paymentReferences[i], _feeAmounts[i], payable(_feeAddress) ); } // amount is updated into batch fee amount amount = (amount * batchFee) / tenThousand; // Check that batch contract has enough funds to pay batch fee require(address(this).balance >= amount, 'not enough funds for batch fee'); // Batch pays batch fee _feeAddress.transfer(amount); // Batch contract transfers the remaining ethers to the payer if (transferBackRemainingEth && address(this).balance > 0) { (bool sendBackSuccess, ) = payable(msg.sender).call{value: address(this).balance}(''); require(sendBackSuccess, 'Could not send remaining funds to the payer'); } } /** * @notice Send a batch of ERC20 payments with fees and paymentReferences to multiple accounts. * @param _tokenAddress Token used for all the payments. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List of payment fee amounts, matching recipients[]. * @param _feeAddress The fee recipient. * @dev Uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure this contract has enough allowance to spend the payer's token. * Make sure the payer has enough tokens to pay the amount, the fee, and the batch fee. */ function batchERC20Payments( address _tokenAddress, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) public { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and fee, and then used as batch fee amount uint256 amount = 0; for (uint256 i = 0; i < _recipients.length; i++) { amount += _amounts[i] + _feeAmounts[i]; } // Transfer the amount and fee from the payer to the batch contract IERC20 requestedToken = IERC20(_tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= amount, 'Insufficient allowance for batch to pay' ); require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds'); require( safeTransferFrom(_tokenAddress, address(this), amount), 'payment transferFrom() failed' ); // Batch contract approve Erc20FeeProxy to spend the token if (requestedToken.allowance(address(this), address(paymentErc20Proxy)) < amount) { approvePaymentProxyToSpend(address(requestedToken), address(paymentErc20Proxy)); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { // amount is updated to become the sum of amounts, to calculate batch fee amount amount -= _feeAmounts[i]; paymentErc20Proxy.transferFromWithReferenceAndFee( _tokenAddress, _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } // amount is updated into batch fee amount amount = (amount * batchFee) / tenThousand; // Check if the payer has enough funds to pay batch fee require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds for the batch fee'); // Payer pays batch fee amount require( safeTransferFrom(_tokenAddress, _feeAddress, amount), 'batch fee transferFrom() failed' ); } /** * @notice Send a batch of ERC20 payments with fees and paymentReferences to multiple accounts, with multiple tokens. * @param _tokenAddresses List of tokens to transact with. * @param _recipients List of recipient accounts. * @param _amounts List of amounts, matching recipients[]. * @param _paymentReferences List of paymentRefs, matching recipients[]. * @param _feeAmounts List of amounts of the payment fee, matching recipients[]. * @param _feeAddress The fee recipient. * @dev It uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure this contract has enough allowance to spend the payer's token. * Make sure the payer has enough tokens to pay the amount, the fee, and the batch fee. */ function batchMultiERC20Payments( address[] calldata _tokenAddresses, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) public { require( _tokenAddresses.length == _recipients.length && _tokenAddresses.length == _amounts.length && _tokenAddresses.length == _paymentReferences.length && _tokenAddresses.length == _feeAmounts.length, 'the input arrays must have the same length' ); // Create a list of unique tokens used and the amounts associated // Only considere tokens having: amounts + feeAmounts > 0 // batchFeeAmount is the amount's sum, and then, batch fee rate is applied Token[] memory uTokens = new Token[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; i++) { for (uint256 j = 0; j < _tokenAddresses.length; j++) { // If the token is already in the existing uTokens list if (uTokens[j].tokenAddress == _tokenAddresses[i]) { uTokens[j].amountAndFee += _amounts[i] + _feeAmounts[i]; uTokens[j].batchFeeAmount += _amounts[i]; break; } // If the token is not in the list (amountAndFee = 0), and amount + fee > 0 if (uTokens[j].amountAndFee == 0 && (_amounts[i] + _feeAmounts[i]) > 0) { uTokens[j].tokenAddress = _tokenAddresses[i]; uTokens[j].amountAndFee = _amounts[i] + _feeAmounts[i]; uTokens[j].batchFeeAmount = _amounts[i]; break; } } } // The payer transfers tokens to the batch contract and pays batch fee for (uint256 i = 0; i < uTokens.length && uTokens[i].amountAndFee > 0; i++) { uTokens[i].batchFeeAmount = (uTokens[i].batchFeeAmount * batchFee) / tenThousand; IERC20 requestedToken = IERC20(uTokens[i].tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= uTokens[i].amountAndFee + uTokens[i].batchFeeAmount, 'Insufficient allowance for batch to pay' ); // check if the payer can pay the amount, the fee, and the batchFee require( requestedToken.balanceOf(msg.sender) >= uTokens[i].amountAndFee + uTokens[i].batchFeeAmount, 'not enough funds' ); // Transfer only the amount and fee required for the token on the batch contract require( safeTransferFrom(uTokens[i].tokenAddress, address(this), uTokens[i].amountAndFee), 'payment transferFrom() failed' ); // Batch contract approves Erc20FeeProxy to spend the token if ( requestedToken.allowance(address(this), address(paymentErc20Proxy)) < uTokens[i].amountAndFee ) { approvePaymentProxyToSpend(address(requestedToken), address(paymentErc20Proxy)); } // Payer pays batch fee amount require( safeTransferFrom(uTokens[i].tokenAddress, _feeAddress, uTokens[i].batchFeeAmount), 'batch fee transferFrom() failed' ); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { paymentErc20Proxy.transferFromWithReferenceAndFee( _tokenAddresses[i], _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } } /* * Helper functions */ /** * @notice Authorizes the proxy to spend a new request currency (ERC20). * @param _erc20Address Address of an ERC20 used as the request currency. * @param _paymentErc20Proxy Address of the proxy. */ function approvePaymentProxyToSpend(address _erc20Address, address _paymentErc20Proxy) internal { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(_paymentErc20Proxy), max); } /** * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call. * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value. * @return result The return value of the ERC20 call, returning true for non-standard tokens */ function safeTransferFrom( address _tokenAddress, address _to, uint256 _amount ) internal returns (bool result) { /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(_tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = _tokenAddress.call( abi.encodeWithSignature('transferFrom(address,address,uint256)', msg.sender, _to, _amount) ); assembly { switch returndatasize() case 0 { // Not a standard erc20 result := 1 } case 32 { // Standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // Anything else, should revert for safety revert(0, 0) } } require(success, 'transferFrom() has been reverted'); /* solium-enable security/no-inline-assembly */ return result; } /* * Admin functions to edit the proxies address and fees */ /** * @notice fees added when using Erc20/Eth batch functions * @param _batchFee between 0 and 10000, i.e: batchFee = 50 represent 0.50% of fee */ function setBatchFee(uint256 _batchFee) external onlyOwner { batchFee = _batchFee; } /** * @param _paymentErc20Proxy The address to the Erc20 fee payment proxy to use. */ function setPaymentErc20Proxy(address _paymentErc20Proxy) external onlyOwner { paymentErc20Proxy = IERC20FeeProxy(_paymentErc20Proxy); } /** * @param _paymentEthProxy The address to the Ethereum fee payment proxy to use. */ function setPaymentEthProxy(address _paymentEthProxy) external onlyOwner { paymentEthProxy = IEthereumFeeProxy(_paymentEthProxy); } }
4,272
183
// converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
function toAsciiString(address addr, uint256 len) internal pure returns (string memory) { require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN"); bytes memory s = new bytes(len); uint256 addrNum = uint256(uint160(addr)); for (uint256 ii = 0; ii < len ; ii +=2) { uint8 b = uint8(addrNum >> (4 * (38 - ii))); s[ii] = char(b >> 4); s[ii + 1] = char(b & 0x0f); } return string(s); }
function toAsciiString(address addr, uint256 len) internal pure returns (string memory) { require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN"); bytes memory s = new bytes(len); uint256 addrNum = uint256(uint160(addr)); for (uint256 ii = 0; ii < len ; ii +=2) { uint8 b = uint8(addrNum >> (4 * (38 - ii))); s[ii] = char(b >> 4); s[ii + 1] = char(b & 0x0f); } return string(s); }
51,496
132
// Get the weight of a Vault
function perVaultRewardsWeight(address vault) external view returns (uint256);
function perVaultRewardsWeight(address vault) external view returns (uint256);
66,765
118
// Returns the SECP256k1 public key associated with an ENS node.Defined in EIP 619. node The ENS node to queryreturn x, y the X and Y coordinates of the curve point for the public key. /
function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); }
function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); }
15,739
104
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
if (asset == mTokenModify) {
16,021
2
// set the rest of the contract variables
router = _router;
router = _router;
4,563
18
// Retrieves all task information by id./_taskId Id of the task.
function getTask( uint256 _taskId ) external view returns (OffChainTask memory);
function getTask( uint256 _taskId ) external view returns (OffChainTask memory);
6,798
85
// ============ Library Functions ============
function that( bool must, bytes32 file, bytes32 reason ) internal pure
function that( bool must, bytes32 file, bytes32 reason ) internal pure
523
54
// uint256 aff; affiliate vault
uint256 lrnd; // last round played
uint256 lrnd; // last round played
16,069
37
// Refund any extra payment
if(msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); }
if(msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); }
6,138
27
// Data structure that holds inforamtion about one of the options for the election.
struct Option { uint64 matchId; string videoURL; string description; address bluePlayer; }
struct Option { uint64 matchId; string videoURL; string description; address bluePlayer; }
55,449
8
// EnvelopeUtils library BGD Labs Defines utility functions for Envelopes /
library EnvelopeUtils { /** * @notice method that encodes an Envelope and generates its id * @param envelope object with the routing information necessary to send a message to a destination chain * @return object containing the encoded envelope and the envelope id */ function encode(Envelope memory envelope) internal pure returns (EncodedEnvelope memory) { EncodedEnvelope memory encodedEnvelope; encodedEnvelope.data = abi.encode(envelope); encodedEnvelope.id = getId(encodedEnvelope.data); return encodedEnvelope; } /** * @notice method to decode and encoded envelope to its raw parameters * @param envelope bytes with the encoded envelope data * @return object with the decoded envelope information */ function decode(bytes memory envelope) internal pure returns (Envelope memory) { return abi.decode(envelope, (Envelope)); } /** * @notice method to get an envelope's id * @param envelope object with the routing information necessary to send a message to a destination chain * @return hash id of the envelope */ function getId(Envelope memory envelope) internal pure returns (bytes32) { EncodedEnvelope memory encodedEnvelope = encode(envelope); return encodedEnvelope.id; } /** * @notice method to get an envelope's id * @param envelope bytes with the encoded envelope data * @return hash id of the envelope */ function getId(bytes memory envelope) internal pure returns (bytes32) { return keccak256(envelope); } }
library EnvelopeUtils { /** * @notice method that encodes an Envelope and generates its id * @param envelope object with the routing information necessary to send a message to a destination chain * @return object containing the encoded envelope and the envelope id */ function encode(Envelope memory envelope) internal pure returns (EncodedEnvelope memory) { EncodedEnvelope memory encodedEnvelope; encodedEnvelope.data = abi.encode(envelope); encodedEnvelope.id = getId(encodedEnvelope.data); return encodedEnvelope; } /** * @notice method to decode and encoded envelope to its raw parameters * @param envelope bytes with the encoded envelope data * @return object with the decoded envelope information */ function decode(bytes memory envelope) internal pure returns (Envelope memory) { return abi.decode(envelope, (Envelope)); } /** * @notice method to get an envelope's id * @param envelope object with the routing information necessary to send a message to a destination chain * @return hash id of the envelope */ function getId(Envelope memory envelope) internal pure returns (bytes32) { EncodedEnvelope memory encodedEnvelope = encode(envelope); return encodedEnvelope.id; } /** * @notice method to get an envelope's id * @param envelope bytes with the encoded envelope data * @return hash id of the envelope */ function getId(bytes memory envelope) internal pure returns (bytes32) { return keccak256(envelope); } }
17,388
320
// Returns the remainder of dividing two unsigned integers, with a division by zero flag. _Available since v3.4._ /
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); }
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); }
74,133
116
// check on the expansionary side
if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe(); }
if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe(); }
29,930
88
// ============ Variables ============ //RNG contract interface
RNGInterface internal rng;
RNGInterface internal rng;
25,366
0
// @custom:legacy Emitted whenever a withdrawal from L2 to L1 is initiated.l1Token Address of the token on L1. l2Token Address of the corresponding token on L2. fromAddress of the withdrawer. toAddress of the recipient on L1. amountAmount of the ERC20 withdrawn. extraData Extra data attached to the withdrawal. /
event WithdrawalInitiated( address indexed l1Token, address indexed l2Token, address indexed from, address to, uint256 amount, bytes extraData );
event WithdrawalInitiated( address indexed l1Token, address indexed l2Token, address indexed from, address to, uint256 amount, bytes extraData );
15,806
138
// Update the order status as not valid and cancelled.
orderStatus.isValidated = false; orderStatus.isCancelled = true;
orderStatus.isValidated = false; orderStatus.isCancelled = true;
17,169
162
// Calculate base 2 logarithm of an unsigned 128-bit integer number.Revertin case x is zero.x number to calculate base 2 logarithm ofreturn base 2 logarithm of x, multiplied by 2^121 /
function log_2(uint128 x)
function log_2(uint128 x)
38,752
990
// return early to save gas
return;
return;
5,459
94
// Fetches Compound collateral factors for tokens/_cTokens Arr. of cTokens for which to get the coll. factors/ return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = Comptroller.markets(_cTokens[i]); } }
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = Comptroller.markets(_cTokens[i]); } }
46,979
217
// File: contracts/IERC721L.sol
pragma solidity ^0.8.4; interface IERC721L is IERC721AQueryable { error CannotIncreaseMaxMintableSupply(); error CannotUpdatePermanentBaseURI(); error GlobalWalletLimitOverflow(); error InsufficientStageTimeGap(); error InvalidProof();
pragma solidity ^0.8.4; interface IERC721L is IERC721AQueryable { error CannotIncreaseMaxMintableSupply(); error CannotUpdatePermanentBaseURI(); error GlobalWalletLimitOverflow(); error InsufficientStageTimeGap(); error InvalidProof();
10,287
14
// return the sender of this call.if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytesof the msg.data.otherwise, return `msg.sender`should be used in the contract anywhere instead of msg.sender /
function _msgSender() internal virtual view returns (address payable); function versionRecipient() external virtual view returns (string memory);
function _msgSender() internal virtual view returns (address payable); function versionRecipient() external virtual view returns (string memory);
10,955
37
// Atomic Token Swaporder Types.Order/
function swap( Types.Order calldata order ) external;
function swap( Types.Order calldata order ) external;
26,196
1
// LendingPool of aave
ILendingPool public lendingPool;
ILendingPool public lendingPool;
19,828
1,127
// Accessor method for a user's collateral. This is necessary because the struct returned by the depositBoxes() method showsrawCollateral, which isn't a user-readable value. user address whose collateral amount is retrieved.return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). /
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); }
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); }
9,550
14
// Transfer `amount` tokens from `msg.sender` to `dst`dst The address of the destination accountamount The number of tokens to transfer return Whether or not the transfer succeeded/
function transfer(address dst, uint256 amount) external returns (bool success);
function transfer(address dst, uint256 amount) external returns (bool success);
12,460
148
// Grab a reference to the Poniesies from storage.
Pony storage sire = Poniesies[_sireId]; Pony storage matron = Poniesies[_matronId];
Pony storage sire = Poniesies[_sireId]; Pony storage matron = Poniesies[_matronId];
12,841
2
// Tells the address of the ownerreturn the address of the owner /
function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; }
function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; }
4,789
41
// MAXINT to be used only, to increase allowance from payment protocol contract towards knowndecentralized exchanges, not to dyanmically called contracts!!!
uint public immutable MAXINT = type(uint256).max;
uint public immutable MAXINT = type(uint256).max;
15,898
10
// node side => nft.setApprovalForAll(msg.sender,true);
onSaleItem memory newItem = onSaleItem({ tokenId: tokenId, owner: msg.sender, sold: false, onSale: true, timeOnsale: block.timestamp, price: value, qty: _qty });
onSaleItem memory newItem = onSaleItem({ tokenId: tokenId, owner: msg.sender, sold: false, onSale: true, timeOnsale: block.timestamp, price: value, qty: _qty });
9,352
51
// Do the transfer from address to address value/from address from/to address to/value uint256
function transferFrom(address from, address to, uint256 value) canTransfer public returns (bool) { return super.transferFrom(from, to, value); }
function transferFrom(address from, address to, uint256 value) canTransfer public returns (bool) { return super.transferFrom(from, to, value); }
33,522
8
// get L1 gas fees paid by the current transaction (txBaseFeeWei, calldataFeeWei)
function getCurrentTxL1GasFees() external view returns(uint);
function getCurrentTxL1GasFees() external view returns(uint);
19,068
96
// Executes buyback burns all allowed tokens and returns back Eth call token.approve before calling this function /
function buyback() public { (uint8 stage,,) = getStage(sold); require(stage > 0, "buyback doesn&#39;t work on stage 0"); uint256 approved = token.allowance(msg.sender, this); uint256 inCirculation = token.totalSupply().sub(token.balanceOf(this)); uint256 value = approved.mul(address(this).balance).div(inCirculation); token.burnFrom(msg.sender, approved); msg.sender.transfer(value); emit Buyback(msg.sender, approved, value); }
function buyback() public { (uint8 stage,,) = getStage(sold); require(stage > 0, "buyback doesn&#39;t work on stage 0"); uint256 approved = token.allowance(msg.sender, this); uint256 inCirculation = token.totalSupply().sub(token.balanceOf(this)); uint256 value = approved.mul(address(this).balance).div(inCirculation); token.burnFrom(msg.sender, approved); msg.sender.transfer(value); emit Buyback(msg.sender, approved, value); }
48,381
33
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
set._values[toDeleteIndex] = lastValue;
11,327
345
// Add incentive
Decimal.D256 memory incentive = dsdCost.mul(Constants.getAdvanceIncentivePremium());
Decimal.D256 memory incentive = dsdCost.mul(Constants.getAdvanceIncentivePremium());
4,250
27
// initializes the contract and its parents /
function __AutoCompoundingRewards_init() internal onlyInitializing { __ReentrancyGuard_init(); __Upgradeable_init(); __AutoCompoundingRewards_init_unchained(); }
function __AutoCompoundingRewards_init() internal onlyInitializing { __ReentrancyGuard_init(); __Upgradeable_init(); __AutoCompoundingRewards_init_unchained(); }
29,973
106
// See `IRelayRecipient.postRelayedCall`. This function should not be overridden directly, use `_postRelayedCall` instead.Requirements: - the caller must be the `RelayHub` contract. /
function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); }
function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); }
6,480
45
// Get accountBurned mapping.
mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)];
mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)];
6,006
189
// Liquidation of an open loan available for anyone
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant pETHRateNotInvalid { require(loanLiquidationOpen, "Liquidation is not open"); // Close the creators loan and send collateral to the closer. _closeLoan(_loanCreatorsAddress, _loanID); // Tell the Dapps this loan was liquidated emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); }
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant pETHRateNotInvalid { require(loanLiquidationOpen, "Liquidation is not open"); // Close the creators loan and send collateral to the closer. _closeLoan(_loanCreatorsAddress, _loanID); // Tell the Dapps this loan was liquidated emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); }
50,068
0
// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]);
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]);
14,330
38
// Adapter class needed to calculate USD value of specific amount of LP tokensthis contract assumes that USD value of only one part of LP pair is eq 1 USD /
contract UniswapAdapterWithOneStable is IAdapter { using SafeMath for uint256; struct LocalVars { address t0; address t1; uint256 totalValue; uint256 supply; uint256 usdPrec; } address public deployer; address public buck; constructor() public { deployer = msg.sender; } function setup(address _buck) public { require(deployer == msg.sender); buck = _buck; deployer = address(0); } function calc( address gem, uint256 value, uint256 factor ) external view returns (uint256) { (uint112 _reserve0, uint112 _reserve1, ) = UniswapV2PairLike(gem).getReserves(); LocalVars memory loc; loc.t0 = UniswapV2PairLike(gem).token0(); loc.t1 = UniswapV2PairLike(gem).token1(); loc.usdPrec = 10**6; if (buck == loc.t0) { loc.totalValue = uint256(_reserve0).mul(loc.usdPrec).div( uint256(10)**IERC20(loc.t0).decimals() ); } else if (buck == loc.t1) { loc.totalValue = uint256(_reserve1).mul(loc.usdPrec).div( uint256(10)**IERC20(loc.t1).decimals() ); } else { require(false, "gem w/o buck"); } loc.supply = UniswapV2PairLike(gem).totalSupply(); return value.mul(loc.totalValue).mul(2).mul(factor).mul(1e18).div( loc.supply.mul(loc.usdPrec) ); } }
contract UniswapAdapterWithOneStable is IAdapter { using SafeMath for uint256; struct LocalVars { address t0; address t1; uint256 totalValue; uint256 supply; uint256 usdPrec; } address public deployer; address public buck; constructor() public { deployer = msg.sender; } function setup(address _buck) public { require(deployer == msg.sender); buck = _buck; deployer = address(0); } function calc( address gem, uint256 value, uint256 factor ) external view returns (uint256) { (uint112 _reserve0, uint112 _reserve1, ) = UniswapV2PairLike(gem).getReserves(); LocalVars memory loc; loc.t0 = UniswapV2PairLike(gem).token0(); loc.t1 = UniswapV2PairLike(gem).token1(); loc.usdPrec = 10**6; if (buck == loc.t0) { loc.totalValue = uint256(_reserve0).mul(loc.usdPrec).div( uint256(10)**IERC20(loc.t0).decimals() ); } else if (buck == loc.t1) { loc.totalValue = uint256(_reserve1).mul(loc.usdPrec).div( uint256(10)**IERC20(loc.t1).decimals() ); } else { require(false, "gem w/o buck"); } loc.supply = UniswapV2PairLike(gem).totalSupply(); return value.mul(loc.totalValue).mul(2).mul(factor).mul(1e18).div( loc.supply.mul(loc.usdPrec) ); } }
41,277
20
// 投注人地址、投注生肖 集合
mapping(uint => ticket[]) lotteryPlayers;
mapping(uint => ticket[]) lotteryPlayers;
8,725
2
// The address every account is opted-in to by default
address private immutable _defaultOptInAddress;
address private immutable _defaultOptInAddress;
701
5
// modifiers
modifier onlyOwner
modifier onlyOwner
37,819
73
// session {Session} - session of the stakesessionId {uint256} - id of the stakeactualEnd {uint256} - the date when the stake was actually been unstaked
function unstakeInternal( Session storage session, uint256 sessionId, uint256 actualEnd ) internal returns (uint256) { uint256 amountOut = unstakeInternalCommon( sessionId, session.amount, session.start,
function unstakeInternal( Session storage session, uint256 sessionId, uint256 actualEnd ) internal returns (uint256) { uint256 amountOut = unstakeInternalCommon( sessionId, session.amount, session.start,
24,275
87
// Returns the base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI, or to the token ID if no specific URI is set for that token ID./
function baseURI() public view virtual returns (string memory) { return _baseURI; }
function baseURI() public view virtual returns (string memory) { return _baseURI; }
32,314
83
// Add a delegate for staker
function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; }
function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; }
47,460
24
// IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses.
address payable receiver = payable(msg.sender); uint amount = pendingWithdrawals[receiver];
address payable receiver = payable(msg.sender); uint amount = pendingWithdrawals[receiver];
10,464
9
// Get paiement for registering and send back additional ETH
if(msg.value > registryPrice) { if(msg.sender.send(msg.value - registryPrice) == false) throw; }
if(msg.value > registryPrice) { if(msg.sender.send(msg.value - registryPrice) == false) throw; }
10,765
17
// 执行利率模型的 execute
interestRateModel.execute(cashPrior(), oldBorrows, reserves); Exp memory rate = Exp(getBorrowRate()).mulScalar(times); uint256 oldIndex = interestIndex; uint256 interest = rate.mulScalarTruncate(oldBorrows);
interestRateModel.execute(cashPrior(), oldBorrows, reserves); Exp memory rate = Exp(getBorrowRate()).mulScalar(times); uint256 oldIndex = interestIndex; uint256 interest = rate.mulScalarTruncate(oldBorrows);
5,833
20
// Registry contract to store registered modulesAnyone can register modules, but only those "approved" by Polymath will be available for issuers to add/
contract ModuleRegistry is IModuleRegistry, Pausable, RegistryUpdater, ReclaimTokens { // Mapping used to hold the type of module factory corresponds to the address of the Module factory contract mapping (address => uint8) public registry; // Mapping used to hold the reputation of the factory mapping (address => address[]) public reputation; // Mapping contain the list of addresses of Module factory for a particular type mapping (uint8 => address[]) public moduleList; // contains the list of verified modules mapping (address => bool) public verified; // Contains the list of the available tags corresponds to the module type mapping (uint8 => bytes32[]) public availableTags; // Emit when Module been used by the securityToken event LogModuleUsed(address indexed _moduleFactory, address indexed _securityToken); // Emit when the Module Factory get registered with the ModuleRegistry contract event LogModuleRegistered(address indexed _moduleFactory, address indexed _owner); // Emit when the module get verified by the Polymath team event LogModuleVerified(address indexed _moduleFactory, bool _verified); constructor (address _polymathRegistry) public RegistryUpdater(_polymathRegistry) { } /** * @notice Called by a security token to notify the registry it is using a module * @param _moduleFactory is the address of the relevant module factory */ function useModule(address _moduleFactory) external { //If caller is a registered security token, then register module usage if (ISecurityTokenRegistry(securityTokenRegistry).isSecurityToken(msg.sender)) { require(registry[_moduleFactory] != 0, "ModuleFactory type should not be 0"); //To use a module, either it must be verified, or owned by the ST owner require(verified[_moduleFactory]||(IModuleFactory(_moduleFactory).owner() == ISecurityToken(msg.sender).owner()), "Module factory is not verified as well as not called by the owner"); reputation[_moduleFactory].push(msg.sender); emit LogModuleUsed (_moduleFactory, msg.sender); } } /** * @notice Called by moduleFactory owner to register new modules for SecurityToken to use * @param _moduleFactory is the address of the module factory to be registered * @return bool */ function registerModule(address _moduleFactory) external whenNotPaused returns(bool) { require(registry[_moduleFactory] == 0, "Module factory should not be pre-registered"); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(moduleFactory.getType() != 0, "Factory type should not equal to 0"); registry[_moduleFactory] = moduleFactory.getType(); moduleList[moduleFactory.getType()].push(_moduleFactory); reputation[_moduleFactory] = new address[](0); emit LogModuleRegistered (_moduleFactory, moduleFactory.owner()); return true; } /** * @notice Called by Polymath to verify modules for SecurityToken to use. * @notice A module can not be used by an ST unless first approved/verified by Polymath * @notice (The only exception to this is that the author of the module is the owner of the ST) * @param _moduleFactory is the address of the module factory to be registered * @return bool */ function verifyModule(address _moduleFactory, bool _verified) external onlyOwner returns(bool) { //Must already have been registered require(registry[_moduleFactory] != 0, "Module factory should have been already registered"); verified[_moduleFactory] = _verified; emit LogModuleVerified(_moduleFactory, _verified); return true; } /** * @notice Use to get all the tags releated to the functionality of the Module Factory. * @param _moduleType Type of module * @return bytes32 array */ function getTagByModuleType(uint8 _moduleType) public view returns(bytes32[]) { return availableTags[_moduleType]; } /** * @notice Add the tag for specified Module Factory * @param _moduleType Type of module. * @param _tag List of tags */ function addTagByModuleType(uint8 _moduleType, bytes32[] _tag) public onlyOwner { for (uint8 i = 0; i < _tag.length; i++) { availableTags[_moduleType].push(_tag[i]); } } /** * @notice remove the tag for specified Module Factory * @param _moduleType Type of module. * @param _removedTags List of tags */ function removeTagByModuleType(uint8 _moduleType, bytes32[] _removedTags) public onlyOwner { for (uint8 i = 0; i < availableTags[_moduleType].length; i++) { for (uint8 j = 0; j < _removedTags.length; j++) { if (availableTags[_moduleType][i] == _removedTags[j]) { delete availableTags[_moduleType][i]; } } } } /** * @notice pause registration function */ function unpause() public onlyOwner { _unpause(); } /** * @notice unpause registration function */ function pause() public onlyOwner { _pause(); } }
contract ModuleRegistry is IModuleRegistry, Pausable, RegistryUpdater, ReclaimTokens { // Mapping used to hold the type of module factory corresponds to the address of the Module factory contract mapping (address => uint8) public registry; // Mapping used to hold the reputation of the factory mapping (address => address[]) public reputation; // Mapping contain the list of addresses of Module factory for a particular type mapping (uint8 => address[]) public moduleList; // contains the list of verified modules mapping (address => bool) public verified; // Contains the list of the available tags corresponds to the module type mapping (uint8 => bytes32[]) public availableTags; // Emit when Module been used by the securityToken event LogModuleUsed(address indexed _moduleFactory, address indexed _securityToken); // Emit when the Module Factory get registered with the ModuleRegistry contract event LogModuleRegistered(address indexed _moduleFactory, address indexed _owner); // Emit when the module get verified by the Polymath team event LogModuleVerified(address indexed _moduleFactory, bool _verified); constructor (address _polymathRegistry) public RegistryUpdater(_polymathRegistry) { } /** * @notice Called by a security token to notify the registry it is using a module * @param _moduleFactory is the address of the relevant module factory */ function useModule(address _moduleFactory) external { //If caller is a registered security token, then register module usage if (ISecurityTokenRegistry(securityTokenRegistry).isSecurityToken(msg.sender)) { require(registry[_moduleFactory] != 0, "ModuleFactory type should not be 0"); //To use a module, either it must be verified, or owned by the ST owner require(verified[_moduleFactory]||(IModuleFactory(_moduleFactory).owner() == ISecurityToken(msg.sender).owner()), "Module factory is not verified as well as not called by the owner"); reputation[_moduleFactory].push(msg.sender); emit LogModuleUsed (_moduleFactory, msg.sender); } } /** * @notice Called by moduleFactory owner to register new modules for SecurityToken to use * @param _moduleFactory is the address of the module factory to be registered * @return bool */ function registerModule(address _moduleFactory) external whenNotPaused returns(bool) { require(registry[_moduleFactory] == 0, "Module factory should not be pre-registered"); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(moduleFactory.getType() != 0, "Factory type should not equal to 0"); registry[_moduleFactory] = moduleFactory.getType(); moduleList[moduleFactory.getType()].push(_moduleFactory); reputation[_moduleFactory] = new address[](0); emit LogModuleRegistered (_moduleFactory, moduleFactory.owner()); return true; } /** * @notice Called by Polymath to verify modules for SecurityToken to use. * @notice A module can not be used by an ST unless first approved/verified by Polymath * @notice (The only exception to this is that the author of the module is the owner of the ST) * @param _moduleFactory is the address of the module factory to be registered * @return bool */ function verifyModule(address _moduleFactory, bool _verified) external onlyOwner returns(bool) { //Must already have been registered require(registry[_moduleFactory] != 0, "Module factory should have been already registered"); verified[_moduleFactory] = _verified; emit LogModuleVerified(_moduleFactory, _verified); return true; } /** * @notice Use to get all the tags releated to the functionality of the Module Factory. * @param _moduleType Type of module * @return bytes32 array */ function getTagByModuleType(uint8 _moduleType) public view returns(bytes32[]) { return availableTags[_moduleType]; } /** * @notice Add the tag for specified Module Factory * @param _moduleType Type of module. * @param _tag List of tags */ function addTagByModuleType(uint8 _moduleType, bytes32[] _tag) public onlyOwner { for (uint8 i = 0; i < _tag.length; i++) { availableTags[_moduleType].push(_tag[i]); } } /** * @notice remove the tag for specified Module Factory * @param _moduleType Type of module. * @param _removedTags List of tags */ function removeTagByModuleType(uint8 _moduleType, bytes32[] _removedTags) public onlyOwner { for (uint8 i = 0; i < availableTags[_moduleType].length; i++) { for (uint8 j = 0; j < _removedTags.length; j++) { if (availableTags[_moduleType][i] == _removedTags[j]) { delete availableTags[_moduleType][i]; } } } } /** * @notice pause registration function */ function unpause() public onlyOwner { _unpause(); } /** * @notice unpause registration function */ function pause() public onlyOwner { _pause(); } }
2,590
16
// Events to log various actions
event HalvingMechanismAddressIsSet(uint256 indexed motionId, address halvingMechanismAddress, bool isMintingAddressSet); event FeeUpdated(uint256 _basisPoints); event FeeDistributed(uint256 liquidityAmount, uint256 timeLockAmount); event Minted(address indexed account, uint256 amount); event Burned(address indexed account, uint256 amount); event ExemptionStatusChanged(address indexed _address, bool _exempt); event EligibilityStatusChanged(address indexed _address, bool _eligible); event TxFeeRewardsDistributed(uint256 periodIndex, uint256 timestamp); event TxFeeRewardClaimed(address indexed account, uint256 amount); event TxFeeRewardForfixedAddresstransfered(address indexed fixedAddress, uint256 amount);
event HalvingMechanismAddressIsSet(uint256 indexed motionId, address halvingMechanismAddress, bool isMintingAddressSet); event FeeUpdated(uint256 _basisPoints); event FeeDistributed(uint256 liquidityAmount, uint256 timeLockAmount); event Minted(address indexed account, uint256 amount); event Burned(address indexed account, uint256 amount); event ExemptionStatusChanged(address indexed _address, bool _exempt); event EligibilityStatusChanged(address indexed _address, bool _eligible); event TxFeeRewardsDistributed(uint256 periodIndex, uint256 timestamp); event TxFeeRewardClaimed(address indexed account, uint256 amount); event TxFeeRewardForfixedAddresstransfered(address indexed fixedAddress, uint256 amount);
2,723
97
// Access methods:
function setTokenManager(address _new) public onlyTokenManager { tokenManager = _new; }
function setTokenManager(address _new) public onlyTokenManager { tokenManager = _new; }
3,151
135
// convert from 3Crv to CCrv (via DAI)
function _convert_3crv_to_shares(uint _3crv) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwap3Pool.remove_liquidity_one_coin(_3crv, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); }
function _convert_3crv_to_shares(uint _3crv) internal returns (uint _shares) { // convert to DAI uint[2] memory amounts; uint _before = cpoolTokens[0].balanceOf(address(this)); stableSwap3Pool.remove_liquidity_one_coin(_3crv, 0, 1); uint _after = cpoolTokens[0].balanceOf(address(this)); amounts[0] = _after.sub(_before); // add DAI to cpool to get back CCrv _before = tokenCCrv.balanceOf(address(this)); depositCompound.add_liquidity(amounts, 1); _after = tokenCCrv.balanceOf(address(this)); _shares = _after.sub(_before); }
64,797
90
// Gets the total amount of tokens stored by the contractreturn uint256 representing the total amount of tokens /
function totalSupply() public view returns (uint256) { return allTokens.length; }
function totalSupply() public view returns (uint256) { return allTokens.length; }
15,687
57
// Usage is calculated in equivalent USD at that time, so same amount of token can have different usage at different time For USD stablecoin, just simply fix it at 1:1
uint256 equivUSD = toEquivalentUSD(amount); uint256 tokenAmount = amount; if (fixedPoolUsageUSD.add(equivUSD) > fixedPoolCapacityUSD) { equivUSD = fixedPoolCapacityUSD.sub(fixedPoolUsageUSD); tokenAmount = toEquivalentToken(equivUSD); }
uint256 equivUSD = toEquivalentUSD(amount); uint256 tokenAmount = amount; if (fixedPoolUsageUSD.add(equivUSD) > fixedPoolCapacityUSD) { equivUSD = fixedPoolCapacityUSD.sub(fixedPoolUsageUSD); tokenAmount = toEquivalentToken(equivUSD); }
20,112
154
// Events//Public Functions//Retrieves the total number of elements submitted.return _totalElements Total submitted elements. /
function getTotalElements() external view returns (uint256 _totalElements);
function getTotalElements() external view returns (uint256 _totalElements);
18,387
153
// offers[id] is not the highest offer
require(_rank[_rank[id].next].prev == id); _rank[_rank[id].next].prev = _rank[id].prev;
require(_rank[_rank[id].next].prev == id); _rank[_rank[id].next].prev = _rank[id].prev;
14,309
173
// Stop copying when the memory counter reaches the new combined length of the arrays.
end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
6,768
115
// Pass data if recipient is contract
if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{ gas: _gasLimit }(msg.sender, _from, _ids, _amounts, _data);
if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{ gas: _gasLimit }(msg.sender, _from, _ids, _amounts, _data);
55,757
236
// The approx amount of gas required to purchase a key
function estimatedGasForPurchase() external view returns (uint);
function estimatedGasForPurchase() external view returns (uint);
13,501
63
//
function _defaultIntervalParams() internal pure virtual returns (uint64 _wait, uint64 _open)
function _defaultIntervalParams() internal pure virtual returns (uint64 _wait, uint64 _open)
1,177
25
// 超发token处理
function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); if (value + currentSupply > totalSupply) throw; currentSupply = safeAdd(currentSupply, value); IncreaseSupply(value); }
function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); if (value + currentSupply > totalSupply) throw; currentSupply = safeAdd(currentSupply, value); IncreaseSupply(value); }
46,707
7
// Accumulated rewards per token at the last checkpoint
uint256 public accumulatedRewardsPerToken;
uint256 public accumulatedRewardsPerToken;
27,264
22
// set status to 2 (for sale)
require(citizensContract.setStatus(_id,2), 'could not set status for sale');
require(citizensContract.setStatus(_id,2), 'could not set status for sale');
36,642
23
// withdrawing all amount of base asset from strategy /
function withdrawFromStrategyAll(bool isRedeem) virtual public onlyOperator{ withdrawFromStrategy(depositedBase, isRedeem); }
function withdrawFromStrategyAll(bool isRedeem) virtual public onlyOperator{ withdrawFromStrategy(depositedBase, isRedeem); }
36,507
192
// ========== INTERNAL FUNCTIONS ========== / From compound's _moveDelegates Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Elena::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Elena::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Elena::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Elena::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
4,595
40
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.Beware that changing an allowance with this method brings the risk that someone may use both the oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: _spender The address which will spend the funds. _value The amount of tokens to be spent. /
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
4,714
25
// ส่งคืนเหรียญให้ทุกคน
airDropToken(0x523B82EC6A1ddcBc83dF85454Ed8018C8327420B,646000 ether); //1 //646,000 airDropToken(0x8AF7f48FfD233187EeCB75BC20F68ddA54182fD7,100000 ether); //2 //746,000 airDropToken(0xeA1a1c9e7c525C8Ed65DEf0D2634fEBBfC1D4cC7,40000 ether); //3 //786,000 airDropToken(0x55176F6F5cEc289823fb0d1090C4C71685AEa9ad,30000 ether); //4 //816,000 airDropToken(0xd25B928962a287B677e30e1eD86638A2ba2D7fbF,20000 ether); //5 //836,000 airDropToken(0xfCf845416c7BDD85A57b635207Bc0287D10F066c,20000 ether); //6 //856,000 airDropToken(0xc26B195f38A99cbf04AF30F628ba20013C604d2E,20000 ether); //7 //876,000 airDropToken(0x137b159F631A215513DC511901982025e32404C2,16000 ether); //8 //892,000 airDropToken(0x2dCe7d86525872AdE3C89407E27e56A6095b12bE,10000 ether); //9 //902,000
airDropToken(0x523B82EC6A1ddcBc83dF85454Ed8018C8327420B,646000 ether); //1 //646,000 airDropToken(0x8AF7f48FfD233187EeCB75BC20F68ddA54182fD7,100000 ether); //2 //746,000 airDropToken(0xeA1a1c9e7c525C8Ed65DEf0D2634fEBBfC1D4cC7,40000 ether); //3 //786,000 airDropToken(0x55176F6F5cEc289823fb0d1090C4C71685AEa9ad,30000 ether); //4 //816,000 airDropToken(0xd25B928962a287B677e30e1eD86638A2ba2D7fbF,20000 ether); //5 //836,000 airDropToken(0xfCf845416c7BDD85A57b635207Bc0287D10F066c,20000 ether); //6 //856,000 airDropToken(0xc26B195f38A99cbf04AF30F628ba20013C604d2E,20000 ether); //7 //876,000 airDropToken(0x137b159F631A215513DC511901982025e32404C2,16000 ether); //8 //892,000 airDropToken(0x2dCe7d86525872AdE3C89407E27e56A6095b12bE,10000 ether); //9 //902,000
28,100
5
// Description: Check if a user is the owner or banner. Used by methods that should only be run by the owner or banner wallets. /
modifier isOwnerOrBanner() { require(_msgSender() == _owner || _msgSender() == _banner, "Caller is not owner or banner"); _; }
modifier isOwnerOrBanner() { require(_msgSender() == _owner || _msgSender() == _banner, "Caller is not owner or banner"); _; }
50,581
156
// Perform purchase restriciton checks. Override if more logic is needed /
function _validatePurchaseRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= startTime, "Purchasing not active"); }
function _validatePurchaseRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= startTime, "Purchasing not active"); }
7,152
163
// Computes the metrics (token price, daily interest) for the current day of year /
function compute () public { uint256 currentTimestamp = block.timestamp; // solhint-disable-line not-rely-on-time uint256 newPeriod = DateUtils.diffDays(startOfYearTimestamp, currentTimestamp); if (newPeriod <= currentPeriod) return; uint256 x = 0; for (uint256 i = currentPeriod + 1; i <= newPeriod; i++) { x++; _records[i].apr = _records[i - 1].apr; _records[i].totalDeposited = _records[i - 1].totalDeposited; uint256 diff = uint256(_records[i - 1].apr) * USDF_DECIMAL_MULTIPLIER * uint256(100) / uint256(365); _records[i].tokenPrice = _records[i - 1].tokenPrice + (diff / uint256(10000)); _records[i].dailyInterest = _records[i - 1].totalDeposited * uint256(_records[i - 1].apr) / uint256(365) / uint256(100); if (x >= 30) break; } currentPeriod += x; }
function compute () public { uint256 currentTimestamp = block.timestamp; // solhint-disable-line not-rely-on-time uint256 newPeriod = DateUtils.diffDays(startOfYearTimestamp, currentTimestamp); if (newPeriod <= currentPeriod) return; uint256 x = 0; for (uint256 i = currentPeriod + 1; i <= newPeriod; i++) { x++; _records[i].apr = _records[i - 1].apr; _records[i].totalDeposited = _records[i - 1].totalDeposited; uint256 diff = uint256(_records[i - 1].apr) * USDF_DECIMAL_MULTIPLIER * uint256(100) / uint256(365); _records[i].tokenPrice = _records[i - 1].tokenPrice + (diff / uint256(10000)); _records[i].dailyInterest = _records[i - 1].totalDeposited * uint256(_records[i - 1].apr) / uint256(365) / uint256(100); if (x >= 30) break; } currentPeriod += x; }
26,105
3
// The swap fee cannot be 100%: calculations that divide by (1-fee) would revert with division by zero. Swap fees close to 100% can still cause reverts when performing join/exit swaps, if the calculated fee amounts exceed the pool's token balances in the Vault. 95% is a very high but safe maximum value, and we want to be permissive to let the owner manage the Pool as they see fit.
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 95e16; // 95%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 95e16; // 95%
18,678
71
// set state
rebalancing = true; emptyAssets();
rebalancing = true; emptyAssets();
57,237
0
// ========== FLAGS
bool migrated; bool initialized;
bool migrated; bool initialized;
10,052
0
// Constructor. admin The address of the admin /
constructor(address admin) { _admin = admin; }
constructor(address admin) { _admin = admin; }
28,375