contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
StrategyUSDTCurve | StrategyUSDTCurve.sol | 0x7865ee2a9fc0e94fbcae1dff3f75604300802945 | Solidity | StrategyUSDTCurve | contract StrategyUSDTCurve {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public bt = address(0x76c5449F4950f6338A393F53CdA8b53B0cd3Ca3a);
address constant public want = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); //USDT
address constant public a3CRVPool = address(0xDeBF20617708857ebe4F679508E7b7863a8A8EeE);
address constant public a3CRVToken = address(0xFd2a8fA60Abd58Efe3EeE34dd494cD491dC14900);
address constant public a3CRVGauge = address(0xd662908ADA2Ea1916B3318327A97eB18aD588b5d);
address constant public CRVMinter = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
address constant public CRV = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address public governance;
address public controller;
uint256 public redeliverynum = 100 * 1e18;
address[] public swap2TokenRouting;
address[] public swap2BTRouting;
modifier onlyController {
require(msg.sender == controller, "!controller");
_;
}
constructor() public {
governance = tx.origin;
controller = 0x03D2079c54967f463Fd6e89E76012F74EBC62615;
swap2BTRouting = [CRV,weth,bt];
swap2TokenRouting = [CRV,weth,want];
IERC20(CRV).approve(unirouter, uint(-1));
}
function deposit() public {
uint _usdt = IERC20(want).balanceOf(address(this));
if (_usdt > 0) {
IERC20(want).safeApprove(a3CRVPool, 0);
IERC20(want).safeApprove(a3CRVPool, _usdt);
ICurveFi(a3CRVPool).add_liquidity([0, 0,_usdt],0,true);
}
uint256 _a3CRV = IERC20(a3CRVToken).balanceOf(address(this));
if(_a3CRV >0){
IERC20(a3CRVToken).safeApprove(a3CRVGauge, 0);
IERC20(a3CRVToken).safeApprove(a3CRVGauge, _a3CRV);
Gauge(a3CRVGauge).deposit(_a3CRV);
}
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external onlyController
{
uint amount = _withdraw(_amount);
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault");
IERC20(want).safeTransfer(_vault, amount);
}
function _withdraw(uint _amount) internal returns(uint) {
uint amount = IERC20(want).balanceOf(address(this));
if (amount < _amount) {
_withdrawSome(_amount.sub(amount));
amount = IERC20(want).balanceOf(address(this));
}
if (amount < _amount){
return amount;
}
return _amount;
}
function _withdrawSome(uint _amount) internal
{
uint256 _a3CRV = _amount.mul(1e18).mul(1e12).div(ICurveFi(a3CRVPool).get_virtual_price());
uint256 _a3CRVBefore = IERC20(a3CRVToken).balanceOf(address(this));
if(_a3CRV > _a3CRVBefore){
uint256 _eCRVGauge = _a3CRV.sub(_a3CRVBefore);
if(_eCRVGauge>IERC20(a3CRVGauge).balanceOf(address(this))){
_eCRVGauge = IERC20(a3CRVGauge).balanceOf(address(this));
}
Gauge(a3CRVGauge).withdraw(_eCRVGauge);
_a3CRV = IERC20(a3CRVToken).balanceOf(address(this));
}
ICurveFi(a3CRVPool).remove_liquidity_one_coin(_a3CRV,2,0,true);
}
function withdrawAll() external onlyController returns (uint balance) {
balance = _withdraw(balanceOf());
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault");
IERC20(want).safeTransfer(_vault, balance);
}
function balanceOfwant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfeCRV() public view returns (uint256) {
return IERC20(a3CRVGauge).balanceOf(address(this)).add(IERC20(a3CRVToken).balanceOf(address(this)));
}
function balanceOfeCRV2ETH() public view returns(uint256) {
return balanceOfeCRV().mul(ICurveFi(a3CRVPool).get_virtual_price()).div(1e18).div(1e12);
}
function balanceOf() public view returns (uint256) {
return balanceOfwant().add(balanceOfeCRV2ETH());
}
function getPending() public view returns (uint256) {
return Gauge(a3CRVGauge).integrate_fraction(address(this)).sub(Mintr(CRVMinter).minted(address(this), a3CRVGauge));
}
function getCRV() public view returns(uint256)
{
return IERC20(CRV).balanceOf(address(this));
}
function harvest() public
{
Mintr(CRVMinter).mint(a3CRVGauge);
redelivery();
}
function redelivery() internal {
uint256 reward = IERC20(CRV).balanceOf(address(this));
if (reward > redeliverynum)
{
uint256 _2weth = reward.mul(80).div(100); //80%
uint256 _2bt = reward.sub(_2weth); //20%
UniswapRouter(unirouter).swapExactTokensForTokens(_2weth, 0, swap2TokenRouting, address(this), now.add(1800));
UniswapRouter(unirouter).swapExactTokensForTokens(_2bt, 0, swap2BTRouting, Controller(controller).rewards(), now.add(1800));
}
deposit();
}
function setredeliverynum(uint256 value) public
{
require(msg.sender == governance, "!governance");
redeliverynum = value;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | withdraw | function withdraw(uint _amount) external onlyController
nt amount = _withdraw(_amount);
dress _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault");
IERC20(want).safeTransfer(_vault, amount);
| // Withdraw partial funds, normally used with a vault withdrawal | LineComment | v0.5.17+commit.d19bba13 | None | bzzr://92ab33b8d162b96dde4279b774e67eebea1f88ee2e09153fa248b2ff4fa7b05b | {
"func_code_index": [
2214,
2487
]
} | 12,600 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | withdraw | function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
| /**
* @dev Enable Contract Owner to withdraw funds from the contract
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
993,
1128
]
} | 12,601 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | withdrawTransfer | function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
| /**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
1239,
1485
]
} | 12,602 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | mintTeamTokens | function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
| /**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
1606,
2150
]
} | 12,603 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | mintTokenAndTransfer | function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
| /**
* @dev Mint any amount of Tokens to another address for free.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
2236,
2926
]
} | 12,604 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | setRevealTimestamp | function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
| /**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
3031,
3158
]
} | 12,605 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | setProvenanceHash | function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
| /**
* @dev Set the provenance hash
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
3213,
3434
]
} | 12,606 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | setContractURI | function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
| /**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
3543,
3686
]
} | 12,607 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | contractURI | function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
| /**
* @dev Get OpenSea metadata
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
3738,
3847
]
} | 12,608 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | setBaseURI | function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
| /**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
3943,
4046
]
} | 12,609 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | flipSaleState | function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
| /**
* @dev Pause sale if active, make active if paused
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
4121,
4212
]
} | 12,610 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | mintTokens | function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| /**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
4334,
5491
]
} | 12,611 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | setStartingIndex | function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
| /**
* @dev Set the starting index for the collection
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
5563,
6243
]
} | 12,612 |
||
WAGMISevenTwentyOne | contracts/SevenTwentyOneVending.sol | 0x3c16452f0175c03cad9c317618b85f1ac0a4dcf4 | Solidity | WAGMISevenTwentyOne | contract WAGMISevenTwentyOne is ERC721, Ownable {
using SafeMath for uint256;
bool public saleIsActive = false;
string public PROVENANCE = 'fda87b2427b54fa172bc8a88a8dc952cb6fbfc008516c11d4d986a1eff4d8194';
string public OPENSEA_STORE_METADATA = 'ipfs://QmZkUbeWgJp19rsFD98tJ7jCdGdXDj16gQwCdKaWNjovUk';
uint256 public constant PER_TOKEN_PRICE = 50000000000000000;
uint256 public constant MAX_TOKEN_ALLOWANCE = 25;
uint256 public MAX_TOTAL_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint256 public startingIndexBlock;
uint256 public startingIndex;
constructor(
string memory _name,
string memory _symbol,
string memory _baseURI,
uint256 _maxNftSupply,
uint256 _saleStart
) ERC721(_name, _symbol) {
MAX_TOTAL_TOKENS = _maxNftSupply;
REVEAL_TIMESTAMP = _saleStart;
_setBaseURI(_baseURI);
}
/**
* @dev Enable Contract Owner to withdraw funds from the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Enable Contract Owner to transfer contract funds to any address of her choosing
*/
function withdrawTransfer(address _to) public onlyOwner {
require(address(_to) != address(this), 'Cannot send funds to the contract itself');
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.
*/
function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Mint any amount of Tokens to another address for free.
*/
function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {
require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');
require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');
require(address(_to) != address(this), 'Cannot mint to contract itself.');
require(address(_to) != address(0), 'Cannot mint to a null address.');
uint256 supply = totalSupply();
for (uint256 i = 0; i < _numberOfTokens; i++) {
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(_to, supply + i);
}
}
}
/**
* @dev Set the timestamp for the collection to reveal itself. Likely not in use.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/**
* @dev Set the provenance hash
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, 'Provenance has already been set, no do-overs!');
PROVENANCE = _provenanceHash;
}
/**
* @dev Set OpenSea metadata per https://docs.opensea.io/docs/contract-level-metadata
*/
function setContractURI(string memory _contractMetadataURI) public onlyOwner {
OPENSEA_STORE_METADATA = _contractMetadataURI;
}
/**
* @dev Get OpenSea metadata
*/
function contractURI() public view returns (string memory) {
return OPENSEA_STORE_METADATA;
}
/**
* @dev Set the IPFS baseURI, including ending `/` where JSON is located
*/
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Vending part of the contract, any address can purchase Tokens based on the contract price.
*/
function mintTokens(uint256 _numberOfTokens) public payable {
require(saleIsActive, 'Sale must be active to mint.');
require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');
require(
totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,
'Purchase would exceed max supply of contract tokens'
);
require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');
for (uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_TOTAL_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
/*
If we haven't set the starting index and this is either
1) the last saleable token or
2) the first token to be sold after
the end of pre-sale, set the starting index block
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, 'Starting index is already set');
require(startingIndexBlock != 0, 'Starting index block must be set');
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_TOTAL_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_TOTAL_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
} | /**
* @title SevenTwentyOneVending.sol
* @dev Extends ERC721 Non-Fungible Token Standard's basic implementation
*/ | NatSpecMultiLine | emergencySetStartingIndexBlock | function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, 'Starting index is already set');
startingIndexBlock = block.number;
}
| /**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | {
"func_code_index": [
6375,
6558
]
} | 12,613 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | LockRequestable | contract LockRequestable {
// MEMBERS
/// @notice the count of all invocations of `generateLockId`.
uint256 public lockRequestCount;
// CONSTRUCTOR
constructor() public {
lockRequestCount = 0;
}
// FUNCTIONS
/** @notice Returns a fresh unique identifier.
*
* @dev the generation scheme uses three components.
* First, the blockhash of the previous block.
* Second, the deployed address.
* Third, the next value of the counter.
* This ensure that identifiers are unique across all contracts
* following this scheme, and that future identifiers are
* unpredictable.
*
* @return a 32-byte unique identifier.
*/
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount));
}
} | /** @title A contract for generating unique identifiers
*
* @notice A contract that provides a identifier generation scheme,
* guaranteeing uniqueness across all contracts that inherit from it,
* as well as unpredictability of future identifiers.
*
* @dev This contract is intended to be inherited by any contract that
* implements the callback software pattern for cooperative custodianship.
*
*/ | NatSpecMultiLine | generateLockId | function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount));
}
| /** @notice Returns a fresh unique identifier.
*
* @dev the generation scheme uses three components.
* First, the blockhash of the previous block.
* Second, the deployed address.
* Third, the next value of the counter.
* This ensure that identifiers are unique across all contracts
* following this scheme, and that future identifiers are
* unpredictable.
*
* @return a 32-byte unique identifier.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
741,
923
]
} | 12,614 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() public view returns (uint256);
| // METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
689,
747
]
} | 12,615 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance);
| // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
828,
906
]
} | 12,616 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) public returns (bool success);
| // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
986,
1068
]
} | 12,617 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
| // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1152,
1253
]
} | 12,618 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) public returns (bool success);
| // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1332,
1418
]
} | 12,619 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Interface | contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) public view returns (uint256 remaining);
| // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1499,
1597
]
} | 12,620 |
||
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | Custodian | contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period of time (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period of time (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2);
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock);
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]]);
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary);
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether);
// disallow using a zero value for the callback address
require(_callbackAddress != address(0));
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0));
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector]);
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1]);
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2]);
require(signer1 != signer2);
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
// ignore send success (assign to `success` but this will be overwritten)
success = msg.sender.send(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId));
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompleteable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector]);
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0));
// `extendRequestTimeLock` must be idempotent
require(request.extended != true);
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
} | /** @title A dual control contract.
*
* @notice A general purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other request must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/ | NatSpecMultiLine | requestUnlock | function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether);
// disallow using a zero value for the callback address
require(_callbackAddress != address(0));
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
| /** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
5029,
7004
]
} | 12,621 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | Custodian | contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period of time (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period of time (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2);
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock);
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]]);
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary);
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether);
// disallow using a zero value for the callback address
require(_callbackAddress != address(0));
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0));
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector]);
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1]);
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2]);
require(signer1 != signer2);
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
// ignore send success (assign to `success` but this will be overwritten)
success = msg.sender.send(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId));
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompleteable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector]);
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0));
// `extendRequestTimeLock` must be idempotent
require(request.extended != true);
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
} | /** @title A dual control contract.
*
* @notice A general purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other request must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/ | NatSpecMultiLine | completeUnlock | function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0));
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector]);
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1]);
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2]);
require(signer1 != signer2);
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
// ignore send success (assign to `success` but this will be overwritten)
success = msg.sender.send(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId));
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
| /** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
7936,
10634
]
} | 12,622 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | Custodian | contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period of time (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period of time (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2);
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock);
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]]);
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary);
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether);
// disallow using a zero value for the callback address
require(_callbackAddress != address(0));
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0));
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector]);
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1]);
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2]);
require(signer1 != signer2);
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
// ignore send success (assign to `success` but this will be overwritten)
success = msg.sender.send(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId));
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompleteable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector]);
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0));
// `extendRequestTimeLock` must be idempotent
require(request.extended != true);
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
} | /** @title A dual control contract.
*
* @notice A general purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other request must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/ | NatSpecMultiLine | deleteUncompletableRequest | function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector]);
delete requestMap[_requestMsgHash];
}
| /** @notice Reclaim the storage of a pending request that is uncompleteable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
11093,
11430
]
} | 12,623 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | Custodian | contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period of time (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period of time (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2);
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock);
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]]);
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary);
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether);
// disallow using a zero value for the callback address
require(_callbackAddress != address(0));
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0));
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector]);
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1]);
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2]);
require(signer1 != signer2);
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
// ignore send success (assign to `success` but this will be overwritten)
success = msg.sender.send(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId));
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompleteable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector]);
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0));
// `extendRequestTimeLock` must be idempotent
require(request.extended != true);
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
} | /** @title A dual control contract.
*
* @notice A general purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other request must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/ | NatSpecMultiLine | extendRequestTimeLock | function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0));
// `extendRequestTimeLock` must be idempotent
require(request.extended != true);
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
| /** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
11800,
12440
]
} | 12,624 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | CustodianUpgradeable | contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
} | /** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
*/ | NatSpecMultiLine | requestCustodianChange | function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
| /** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1223,
1624
]
} | 12,625 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | CustodianUpgradeable | contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
} | /** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
*/ | NatSpecMultiLine | confirmCustodianChange | function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
| /** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2021,
2267
]
} | 12,626 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | CustodianUpgradeable | contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
} | /** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
*/ | NatSpecMultiLine | getCustodianChangeReq | function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return changeRequest.proposedNew;
}
| // PRIVATE FUNCTIONS | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2296,
2721
]
} | 12,627 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20ImplUpgradeable | contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl));
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
//EVENTS
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
} | /** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be be replaced,
* which constitutes an implementation upgrade.
*
*/ | NatSpecMultiLine | requestImplChange | function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
| /** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1222,
1583
]
} | 12,628 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20ImplUpgradeable | contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl));
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
//EVENTS
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
} | /** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be be replaced,
* which constitutes an implementation upgrade.
*
*/ | NatSpecMultiLine | confirmImplChange | function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
| /** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1985,
2220
]
} | 12,629 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20ImplUpgradeable | contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl));
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
//EVENTS
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
} | /** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be be replaced,
* which constitutes an implementation upgrade.
*
*/ | NatSpecMultiLine | getImplChangeReq | function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
| // PRIVATE FUNCTIONS | LineComment | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2249,
2672
]
} | 12,630 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
| /** @notice Returns the total token supply.
*
* @return the total token supply.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
809,
916
]
} | 12,631 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
| /** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1108,
1239
]
} | 12,632 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | emitTransfer | function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
| /** @dev Internal use only.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1285,
1424
]
} | 12,633 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
| /** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1718,
1988
]
} | 12,634 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
| /** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2354,
2707
]
} | 12,635 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | emitApproval | function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
| /** @dev Internal use only.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2753,
2904
]
} | 12,636 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
| /** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
3246,
3528
]
} | 12,637 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
| /** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
3958,
4268
]
} | 12,638 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | decreaseApproval | function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
| /** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
4690,
5010
]
} | 12,639 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Proxy | contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true );
require(erc20Impl.blocked(_from) != true );
require(erc20Impl.blocked(_to) != true );
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
require(erc20Impl.blocked(msg.sender) != true);
require(erc20Impl.blocked(_spender) != true );
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
} | /** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
| /** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
5196,
5357
]
} | 12,640 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Store | contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
} | /** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/ | NatSpecMultiLine | setTotalSupply | function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
| /** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
869,
1026
]
} | 12,641 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Store | contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
} | /** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/ | NatSpecMultiLine | setAllowance | function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
| /** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
1546,
1749
]
} | 12,642 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Store | contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
} | /** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/ | NatSpecMultiLine | setBalance | function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
| /** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2125,
2300
]
} | 12,643 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Store | contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
} | /** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/ | NatSpecMultiLine | addBalance | function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
| /** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2749,
2953
]
} | 12,644 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | approveWithSender | function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
| /** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2891,
3274
]
} | 12,645 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | increaseApprovalWithSender | function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
| /** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
3757,
4361
]
} | 12,646 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | decreaseApprovalWithSender | function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
| /** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
4843,
5491
]
} | 12,647 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | requestPrint | function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
| /** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
6199,
6567
]
} | 12,648 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | confirmPrint | function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
| /** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
7105,
7915
]
} | 12,649 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | burn | function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
| /** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
8206,
8674
]
} | 12,650 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | burn | function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
| /** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
9139,
9878
]
} | 12,651 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | batchTransfer | function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
| /** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
10970,
11812
]
} | 12,652 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | enableSweep | function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
| /** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
12862,
14031
]
} | 12,653 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | replaySweep | function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
| /** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
14743,
15591
]
} | 12,654 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | transferFromWithSender | function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
| /** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
16065,
16815
]
} | 12,655 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | transferWithSender | function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
| /** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
17281,
17817
]
} | 12,656 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | transfer | function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
| /** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
18289,
19019
]
} | 12,657 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
| /// @notice Core logic of the ERC20 `totalSupply` function. | NatSpecSingleLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
19132,
19240
]
} | 12,658 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
| /// @notice Core logic of the ERC20 `balanceOf` function. | NatSpecSingleLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
19307,
19438
]
} | 12,659 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
| /// @notice Core logic of the ERC20 `allowance` function. | NatSpecSingleLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
19505,
19665
]
} | 12,660 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | blockWallet | function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
| /// @dev internal use only. | NatSpecSingleLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
19701,
19850
]
} | 12,661 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | ERC20Impl | contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweep message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0));
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true);
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, 0);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, balance, _value - balance);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
require(blocked[msg.sender] != true);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
require(blocked[to] != true);
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transfered to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
require(blocked[_to] != true);
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true);
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Tranfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transfered.
*
* @dev If suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function transfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event Wiped(address _from, uint256 _value, uint256 _remainder);
/// @dev Emitted by successful `requestPrint` calls.
} | /** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/ | NatSpecMultiLine | unblockWallet | function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
| /// @dev internal use only. | NatSpecSingleLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
19886,
20038
]
} | 12,662 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | limitedPrint | function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
| /** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
2877,
3268
]
} | 12,663 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | requestWipe | function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
| /** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
3768,
4249
]
} | 12,664 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | confirmWipe | function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
| /** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
4573,
5033
]
} | 12,665 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | requestTransfer | function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
| /** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
5561,
5919
]
} | 12,666 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | confirmTransfer | function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
| /** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
6252,
6656
]
} | 12,667 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | requestCeilingRaise | function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
| /** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
7068,
7388
]
} | 12,668 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | confirmCeilingRaise | function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
| /** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
7881,
8535
]
} | 12,669 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | lowerCeiling | function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
| /** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
8965,
9280
]
} | 12,670 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | confirmPrintProxy | function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
| /** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
9942,
10062
]
} | 12,671 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | confirmCustodianChangeProxy | function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
| /** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
10745,
10885
]
} | 12,672 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | blockWallet | function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
| /** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
11104,
11291
]
} | 12,673 |
PrintLimiter | PrintLimiter.sol | 0xf19eab58393609df5f5267486f92ac07522c2bf4 | Solidity | PrintLimiter | contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending transfers.
struct transfer {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or transfer funds from them.
*/
address public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending transfers.
mapping (bytes32 => transfer) public pendingTransferMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian));
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from The array of suspected accounts.
*
* @param _value array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
uint256 amount = _from.length;
for(uint256 i = 0; i < amount; i++) {
address from = _from[i];
uint256 value = _value[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests transfer from suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only linitedPrinter can call this function, and confirming the request is authorized
* by the custodian.
*
* @param _from address of suspected accounts.
*
* @param _to address of reciever.
*
* @param _value amount which will be transfered.
*
* @return lockId A unique identifier for this request.
*/
function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0);
pendingTransferMap[lockId] = transfer(_value, _from, _to);
emit TransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is tranferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingTransferMap[_lockId].from;
address to = pendingTransferMap[_lockId].to;
uint256 value = pendingTransferMap[_lockId].value;
delete pendingTransferMap[_lockId];
erc20Impl.transfer(from, to, value);
emit TransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be blocked.
*/
function blockWallet(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/
function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `block` calls.
event Blocked(address wallet);
/// @dev Emitted by successful `unblock` calls.
event Unblocked(address wallet);
/// @dev Emitted by successful `requestTransfer` calls.
event TransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmTransfer` calls.
event TransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | /** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/ | NatSpecMultiLine | unblock | function unblock(address wallet) public {
require(custodian.signerSet(msg.sender) == true);
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
| /** @notice Unblocks all transactions with wallet.
*
* @dev Only signers from custodian are authorised t ocall this function
*
* @param wallet wallet which will be unblocked.
*/ | NatSpecMultiLine | v0.5.10+commit.5a6ea5b1 | None | bzzr://fe84821aafea4abef06f77a7de5ce773255cb3c427f82d03457d0ffff0a71078 | {
"func_code_index": [
11513,
11700
]
} | 12,674 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | setRouter | function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
| /// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
770,
878
]
} | 12,675 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | mintTo | function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
| /**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
1017,
1188
]
} | 12,676 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | delegatedMintTo | function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
| /**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
1328,
1555
]
} | 12,677 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | setProxyRegistryAddress | function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
| /**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
1668,
1817
]
} | 12,678 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | _getNextTokenId | function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
| /**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
1960,
2071
]
} | 12,679 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | _incrementTokenId | function _incrementTokenId() private {
_currentTokenId++;
}
| /**
* @dev increments the value of _currentTokenId
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
2145,
2223
]
} | 12,680 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | isApprovedForAll | function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
| /**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
2623,
3073
]
} | 12,681 |
NFT | contracts/ERC721Tradable.sol | 0xcabf0ecc15942e2de60f3824b83d0e24dd274b57 | Solidity | ERC721Tradable | abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
address public routerAddress;
uint256 private _currentTokenId = 0;
modifier onlyRouter() {
require(msg.sender == routerAddress, "You are not Router");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/// @dev Assigns a new address to act as the Router. Only available to the current CEO.
/// @param _newRouter The address of the new Router
function setRouter(address _newRouter) external onlyOwner {
routerAddress = _newRouter;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public onlyOwner {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function delegatedMintTo(address _to) public onlyRouter returns (uint256) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
return newTokenId;
}
/**
* @dev set proxy.
* @param _proxyRegistryAddress address of the proxy registry
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/token/", Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
} | /**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/ | NatSpecMultiLine | _msgSender | function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
| /**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://224a73f41a4908869c0dc5ecce7d7719876732740935e9927c62f1c5ea63ea29 | {
"func_code_index": [
3212,
3378
]
} | 12,682 |
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
90,
486
]
} | 12,683 |
|
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
598,
877
]
} | 12,684 |
|
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| /**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
992,
1131
]
} | 12,685 |
|
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
| /**
* @dev Adds two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
1196,
1335
]
} | 12,686 |
|
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| /**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
1470,
1587
]
} | 12,687 |
|
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | initialParameter | function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
| //Init Parameter. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
3621,
4734
]
} | 12,688 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | approveNextOwner | function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
| // Standard contract ownership transfer implementation, | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
4799,
4948
]
} | 12,689 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | function () public payable {
}
| // Fallback function deliberately left empty. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
5124,
5164
]
} | 12,690 |
||||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | createSignerList | function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
| //Creat SignerList. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
5195,
5433
]
} | 12,691 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | createWithdrawalMode | function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
| //Creat WithdrawalMode. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
5470,
5774
]
} | 12,692 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | setSecretSigner | function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
| //Set SecretSigner. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
5807,
5927
]
} | 12,693 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | setSigner | function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
| //Set settle signer. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
5960,
6082
]
} | 12,694 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | setRefunder | function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
| //Set Refunder. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
6110,
6214
]
} | 12,695 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | setTokenAddress | function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
| //Set tokenAddress. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
6247,
6373
]
} | 12,696 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | setMaxProfit | function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
| // Change max bet reward. Setting this to zero effectively disables betting. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
6459,
6625
]
} | 12,697 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | withdrawFunds | function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
| // Funds withdrawal. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
6654,
7083
]
} | 12,698 |
|||
Play0x_LottoBall | Play0x_LottoBall.sol | 0x892552275e5d68d889a33ad119af86b7ddf7c237 | Solidity | Play0x_LottoBall | contract Play0x_LottoBall {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint40;
using SafeMath for uint8;
uint public jackpotSize;
uint public MIN_BET;
uint public MAX_BET;
uint public MAX_AMOUNT;
uint constant MAX_MODULO = 15;
//Adjustable max bet profit.
uint public maxProfit;
//Fee percentage
uint8 public platformFeePercentage = 15;
uint8 public jackpotFeePercentage = 5;
uint8 public ERC20rewardMultiple = 5;
//0:ether 1:token
uint8 public currencyType = 0;
//Bets can be refunded via invoking refundBet.
uint constant BetExpirationBlocks = 250;
//Funds that are locked in potentially winning bets.
uint public lockedInBets;
//Standard contract ownership transfer.
address public owner;
address private nextOwner;
address public secretSigner;
address public refunder;
//The address corresponding to a private key used to sign placeBet commits.
address public ERC20ContractAddres;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//Single bet.
struct Bet {
//Amount in wei.
uint amount;
//place tx Block number.
uint40 placeBlockNumber;
// Address of a gambler.
address gambler;
// Game mode.
uint8 machineMode;
// Number of draws
uint8 rotateTime;
}
//Mapping from commits
mapping (uint => Bet) public bets;
//Mapping from signer
mapping(address => bool) public signerList;
//Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
//Admin Payment
event ToManagerPayment(address indexed beneficiary, uint amount);
event ToManagerFailedPayment(address indexed beneficiary, uint amount);
event ToOwnerPayment(address indexed beneficiary, uint amount);
event ToOwnerFailedPayment(address indexed beneficiary, uint amount);
//Bet Payment
event Payment(address indexed beneficiary, uint amount);
event AllFundsPayment(address indexed beneficiary, uint amount);
event AllTokenPayment(address indexed beneficiary, uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event TokenPayment(address indexed beneficiary, uint amount);
//JACKPOT
event JackpotBouns(address indexed beneficiary, uint amount);
// Events that are issued to make statistic recovery easier.
event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime,uint commit);
//Play0x_LottoBall_Event
event BetRelatedData(
address indexed player,
uint playerBetAmount,
uint playerGetAmount,
bytes32 entropy,
uint8 rotateTime
);
//Refund_Event
event RefundLog(address indexed player, uint commit, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
ERC20ContractAddres = DUMMY_ADDRESS;
refunder = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner);
_;
}
modifier onlyRefunder {
require (msg.sender == refunder);
_;
}
modifier onlySigner {
require (signerList[msg.sender] == true);
_;
}
//Init Parameter.
function initialParameter(
// address _manager,
address _secretSigner,
address _erc20tokenAddress ,
address _refunder,
uint _MIN_BET,
uint _MAX_BET,
uint _maxProfit,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint8 _ERC20rewardMultiple,
uint8 _currencyType,
address[] _signerList,
uint32[] _withdrawalMode)public onlyOwner{
secretSigner = _secretSigner;
ERC20ContractAddres = _erc20tokenAddress;
refunder = _refunder;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
maxProfit = _maxProfit;
MAX_AMOUNT = _MAX_AMOUNT;
platformFeePercentage = _platformFeePercentage;
jackpotFeePercentage = _jackpotFeePercentage;
ERC20rewardMultiple = _ERC20rewardMultiple;
currencyType = _currencyType;
createSignerList(_signerList);
createWithdrawalMode(_withdrawalMode);
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Fallback function deliberately left empty.
function () public payable {
}
//Creat SignerList.
function createSignerList(address[] _signerList)private onlyOwner {
for (uint i=0; i<_signerList.length; i++) {
address newSigner = _signerList[i];
signerList[newSigner] = true;
}
}
//Creat WithdrawalMode.
function createWithdrawalMode(uint32[] _withdrawalMode)private onlyOwner {
for (uint8 i=0; i<_withdrawalMode.length; i++) {
uint32 newWithdrawalMode = _withdrawalMode[i];
uint8 mode = i + 1;
withdrawalMode[mode] = newWithdrawalMode;
}
}
//Set SecretSigner.
function setSecretSigner(address _secretSigner) external onlyOwner {
secretSigner = _secretSigner;
}
//Set settle signer.
function setSigner(address signer,bool isActive )external onlyOwner{
signerList[signer] = isActive;
}
//Set Refunder.
function setRefunder(address _refunder) external onlyOwner {
refunder = _refunder;
}
//Set tokenAddress.
function setTokenAddress(address _tokenAddress) external onlyOwner {
ERC20ContractAddres = _tokenAddress;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
require (_maxProfit < MAX_AMOUNT && _maxProfit > 0);
maxProfit = _maxProfit;
}
// Funds withdrawal.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance && withdrawAmount > 0);
uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount );
}
// Token withdrawal.
function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
//Recovery of funds
function withdrawAllFunds(address beneficiary) external onlyOwner {
if (beneficiary.send(address(this).balance)) {
lockedInBets = 0;
jackpotSize = 0;
emit AllFundsPayment(beneficiary, address(this).balance);
} else {
emit FailedPayment(beneficiary, address(this).balance);
}
}
//Recovery of Token funds
function withdrawAlltokenFunds(address beneficiary) external onlyOwner {
ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
lockedInBets = 0;
jackpotSize = 0;
emit AllTokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this)));
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function getContractInformation()public view returns(
uint _jackpotSize,
uint _MIN_BET,
uint _MAX_BET,
uint _MAX_AMOUNT,
uint8 _platformFeePercentage,
uint8 _jackpotFeePercentage,
uint _maxProfit,
uint _lockedInBets){
_jackpotSize = jackpotSize;
_MIN_BET = MIN_BET;
_MAX_BET = MAX_BET;
_MAX_AMOUNT = MAX_AMOUNT;
_platformFeePercentage = platformFeePercentage;
_jackpotFeePercentage = jackpotFeePercentage;
_maxProfit = maxProfit;
_lockedInBets = lockedInBets;
}
function getContractAddress()public view returns(
address _owner,
address _ERC20ContractAddres,
address _secretSigner,
address _refunder ){
_owner = owner;
_ERC20ContractAddres = ERC20ContractAddres;
_secretSigner = secretSigner;
_refunder = refunder;
}
//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.
function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);
require (lockedInBets.add(jackpotSize) <= address(this).balance);
//Amount should be within range
require (msg.value >= MIN_BET && msg.value <= MAX_BET);
emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = msg.value;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = msg.sender;
bet.machineMode = uint8(_machineMode);
bet.rotateTime = uint8(_rotateTime);
}
function placeTokenBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint _amount, address _playerAddress) external onlySigner {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[_commit];
require (bet.gambler == address(0));
//Check SecretSigner.
bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s));
//Check rotateTime ,machineMode and commitLastBlock.
require (_rotateTime > 0 && _rotateTime <= 20);
//_machineMode: 1~15
require (_machineMode > 0 && _machineMode <= MAX_MODULO);
require (block.number < _commitLastBlock );
//Token lockedInBets
lockedInBets = lockedInBets.add(getPossibleWinPrize(withdrawalMode[_machineMode],_amount));
//Check the highest profit
require (getPossibleWinPrize(withdrawalMode[_machineMode],_amount) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],_amount) > 0);
require (lockedInBets.add(jackpotSize) <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
//Amount should be within range
require (_amount >= MIN_BET && _amount <= MAX_BET);
emit PlaceBetLog(_playerAddress, _amount, _rotateTime,_commit);
// Store bet parameters on blockchain.
bet.amount = _amount;
bet.placeBlockNumber = uint40(block.number);
bet.gambler = _playerAddress;
bet.machineMode = _machineMode;
bet.rotateTime = _rotateTime;
}
function settleBet(bytes32 luckySeed,uint reveal, bytes32 blockHash ) external onlySigner{
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
// Check that bet is in 'active' state and check that bet has not expired yet.
require (bet.amount != 0);
require (bet.rotateTime > 0 && bet.rotateTime <= 20);
require (bet.machineMode > 0 && bet.machineMode <= MAX_MODULO);
require (block.number > bet.placeBlockNumber);
require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks));
require (blockhash(bet.placeBlockNumber) == blockHash);
//check possibleWinAmount
require (getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount) < maxProfit);
require (luckySeed > 0);
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
bytes32 _entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
//Player profit
uint totalAmount = 0;
//Player Token profit
uint totalTokenAmount = 0;
//Jackpot check default value
bool isGetJackpot = false;
//Settlement record
bytes32 tmp_entropy = _entropy;
//Billing mode
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
//Player get Jackpot
if (isGetJackpot == true ) {
emit JackpotBouns(bet.gambler,jackpotSize);
totalAmount = totalAmount.add(jackpotSize);
jackpotSize = 0;
}
if (currencyType == 0) {
//Ether game
if (totalAmount != 0 && totalAmount < maxProfit){
sendFunds(bet.gambler, totalAmount );
}
//Send ERC20 Token
if (totalTokenAmount != 0){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount);
emit TokenPayment(bet.gambler, totalTokenAmount);
}
}
}else if(currencyType == 1){
//ERC20 game
//Send ERC20 Token
if (totalAmount != 0 && totalAmount < maxProfit){
if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount);
emit TokenPayment(bet.gambler, totalAmount);
}
}
}
//Unlock the bet amount, regardless of the outcome.
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount));
//Save jackpotSize
jackpotSize = jackpotSize.add(bet.amount.mul(jackpotFeePercentage).div(1000));
emit BetRelatedData(
bet.gambler,
bet.amount,
totalAmount,
_entropy,
bet.rotateTime
);
//Move bet into 'processed' state already.
bet.amount = 0;
}
function runRotateTime (Bet storage bet, bytes32 _entropy )private view returns(uint totalAmount, uint totalTokenAmount, bool isGetJackpot ) {
bytes32 tmp_entropy = _entropy;
isGetJackpot = false;
uint8 machineMode = bet.machineMode;
for (uint8 i = 0; i < bet.rotateTime; i++) {
//every round result
bool isWinThisRound = false;
//Random number of must be less than the machineMode
assembly {
switch gt(machineMode,and(tmp_entropy, 0xf))
case 1 {
isWinThisRound := 1
}
}
if (isWinThisRound == true ){
//bet win, get single round bonus
totalAmount = totalAmount.add(getPossibleWinPrize(withdrawalMode[bet.machineMode],bet.amount).div(bet.rotateTime));
//Platform fee determination:Ether Game Winning players must pay platform fees
totalAmount = totalAmount.sub(
(
(
bet.amount.div(bet.rotateTime)
).mul(platformFeePercentage)
).div(1000)
);
}else if ( isWinThisRound == false && currencyType == 0 && ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){
//Ether game lose, get token reward
totalTokenAmount = totalTokenAmount.add(bet.amount.div(bet.rotateTime).mul(ERC20rewardMultiple));
}
//Get jackpotWin Result, only one chance to win Jackpot in each game.
if (isGetJackpot == false){
//getJackpotWinBonus
assembly {
let buf := and(tmp_entropy, 0xffff)
switch buf
case 0xffff {
isGetJackpot := 1
}
}
}
//This round is settled, shift settlement record.
tmp_entropy = tmp_entropy >> 4;
}
if (isGetJackpot == true ) {
//gambler get jackpot.
totalAmount = totalAmount.add(jackpotSize);
}
}
//Get deductedBalance
function getPossibleWinPrize(uint bonusPercentage,uint senderValue)public pure returns (uint possibleWinAmount) {
//Win Amount
possibleWinAmount = ((senderValue.mul(bonusPercentage))).div(10000);
}
//Get deductedBalance
function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {
//Platform Fee
uint prePlatformFee = (senderValue).mul(platformFeePercentage);
platformFee = (prePlatformFee).div(1000);
//Get jackpotFee
uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);
jackpotFee = (preJackpotFee).div(1000);
//Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage);
possibleWinAmount = preUserGetAmount.div(10000);
}
function settleBetVerifi(bytes32 luckySeed,uint reveal,bytes32 blockHash )external view onlySigner returns(uint totalAmount,uint totalTokenAmount,bytes32 _entropy,bool isGetJackpot ) {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Bet storage bet = bets[commit];
//The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256.
_entropy = keccak256(
abi.encodePacked(
uint(
keccak256(
abi.encodePacked(
reveal,
luckySeed
)
)
),
blockHash
)
);
isGetJackpot = false;
(totalAmount,totalTokenAmount,isGetJackpot) = runRotateTime(
bet,
_entropy
);
}
// Refund transaction
function refundBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
//Refund
emit RefundLog(bet.gambler,commit, amount);
sendFunds(bet.gambler, amount );
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
function refundTokenBet(uint commit) external onlyRefunder{
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint8 machineMode = bet.machineMode;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));
//Amount unlock
lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));
emit RefundLog(bet.gambler,commit, amount);
//Refund
emit TokenPayment(bet.gambler, amount);
ERC20(ERC20ContractAddres).transfer(bet.gambler, amount);
// Move bet into 'processed' state, release funds.
bet.amount = 0;
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external onlyRefunder {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
// Do not overwrite active bets with zeros
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {
return;
}
// Zero out the remaining storage
bet.placeBlockNumber = 0;
bet.gambler = address(0);
bet.machineMode = 0;
bet.rotateTime = 0;
}
// Helper routine to process the payment.
function sendFunds(address receiver, uint amount ) private {
if (receiver.send(amount)) {
emit Payment(receiver, amount);
} else {
emit FailedPayment(receiver, amount);
}
}
function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner {
if (beneficiary.send(amount)) {
emit ToOwnerPayment(beneficiary, amount);
} else {
emit ToOwnerFailedPayment(beneficiary, amount);
}
}
//Update
function updateMIN_BET(uint _uintNumber)external onlyOwner {
MIN_BET = _uintNumber;
}
function updateMAX_BET(uint _uintNumber)external onlyOwner {
MAX_BET = _uintNumber;
}
function updateMAX_AMOUNT(uint _uintNumber)external onlyOwner {
MAX_AMOUNT = _uintNumber;
}
function updateWithdrawalMode(uint8 _mode, uint32 _modeValue) external onlyOwner{
withdrawalMode[_mode] = _modeValue;
}
function updatePlatformFeePercentage(uint8 _platformFeePercentage ) external onlyOwner{
platformFeePercentage = _platformFeePercentage;
}
function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) external onlyOwner{
jackpotFeePercentage = _jackpotFeePercentage;
}
function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) external onlyOwner{
ERC20rewardMultiple = _ERC20rewardMultiple;
}
function updateCurrencyType(uint8 _currencyType ) external onlyOwner{
currencyType = _currencyType;
}
function updateJackpot(uint newSize) external onlyOwner {
require (newSize < address(this).balance && newSize > 0);
jackpotSize = newSize;
}
} | withdrawToken | function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
uint safetyAmount = jackpotSize.add(lockedInBets);
safetyAmount = safetyAmount.add(withdrawAmount);
require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this)));
ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount);
emit TokenPayment(beneficiary, withdrawAmount);
}
| // Token withdrawal. | LineComment | v0.4.24+commit.e67f0147 | bzzr://b654f22f57aa857a1fab23118d87f2f9641b8a0d78456353eeb05e0ca95fb071 | {
"func_code_index": [
7112,
7643
]
} | 12,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.